我正在尝试使用@overload
传达不同的调用函数的方式,但是在类型注释中,用简单的else
语句在代码中轻松传达的内容是不可能的。没有“ else”的MyPy(正确)抱怨过载版本不匹配(例如,请参见下面的代码段)。
error: Overloaded function signatures 1 and 2 overlap with incompatible return types
我是否正确理解该问题没有好的解决方案?
例如这是一个简单的例子:
ListOrTuple = TypeVar("ListOrTuple", List, Tuple)
# unfortunately, typing doesn't support "anything else" at the moment
# https://github.com/python/typing/issues/599#issuecomment-586007066
AnythingElse = TypeVar("AnythingElse")
# what I would like to have is something like AnythingElse= TypeVar("AnythingElse", Not[List,Tuple])
@overload
def as_list(val: ListOrTuple) -> ListOrTuple:
...
@overload
def as_list(val: AnythingElse) -> List[AnythingElse]:
...
def as_list(val):
"""Return list/tuple as is, otherwise wrap in a list
>>> as_list("test")
['test']
"""
return val if isinstance(val, (list, tuple)) else [val]
这是我的解决方法。它对我来说足够好,但我一点都不喜欢。
# attempt to list all the "other" possible types
AnythingElse = TypeVar("AnythingElse", Set, Mapping, type, int, str, None, Callable, Set, Deque, ByteString)
ListOrTuple = TypeVar("ListOrTuple", List, Tuple, Sequence)
@overload
def as_list(val: ListOrTuple) -> ListOrTuple:
...
@overload
def as_list(val: AnythingElse) -> List[AnythingElse]:
...
def as_list(val):
"""Return list/tuple as is, otherwise wrap in a list
>>> as_list("test")
['test']
"""
return val if isinstance(val, (list, tuple)) else [val]