【发布时间】:2020-05-31 21:52:09
【问题描述】:
我有一个获取对象列表并打印出来的函数。
bc_directives = t.Union[
data.Open,
data.Close,
data.Commodity,
data.Balance,
data.Pad,
data.Transaction,
data.Note,
data.Event,
data.Query,
data.Price,
data.Document,
data.Custom,
]
def print_entries(entries: t.List[bc_directives], file: t.IO) -> None:
pass
但如果我这样做:
accounts: t.List[bc_directives] = []
for entry in data.sorted(entries):
if isinstance(entry, data.Open):
accounts.append(entry)
continue
accounts = sorted(accounts, key=lambda acc: acc.account)
# the attribute account does not exist for the other class.
print_entries(accounts)
这里我有一个问题。 mypy 抱怨其他类没有帐户属性。当然是这样设计的。
“Union[Open, Close, Commodity, Balance, Pad, Transaction, Note, Event, Query, Price, Document, Custom]”的“商品”项没有“账户”属性
如果我将帐户的定义更改为t.List[data.Open],当我使用print_entries 时,mypy 会报错。 (但它应该是最好的)。
那么如何使用联合的子集并让 mypy 不抱怨呢?
【问题讨论】: