如何输入一个接受类或类实例并返回该类实例的函数?
我想输入一个可以采用类类型或类实例的函数,然后返回同一类的实例。例如:
from typing import Type, TypeVar, Union
DT = TypeVar("DT")
def tmap(dest_type_or_obj: Union[DT, Type[DT]]) -> DT:
if isinstance(dest_type_or_obj, type):
dest_obj = dest_type_or_obj()
else:
dest_obj = dest_type_or_obj
return dest_obj
class Dest:
pass
instance_dest = tmap(Dest()) # Works fine
type_dest = tmap(Dest) # [arg-type] mypy(error)
# Argument 2 to "map" of "ObjectMapper" has incompatible type "Type[Dest]"; expected "Type[<nothing>]"
I want to type a function that can take either a class type, or an instance of the class, and then return an instance of that same class. For example:
from typing import Type, TypeVar, Union
DT = TypeVar("DT")
def tmap(dest_type_or_obj: Union[DT, Type[DT]]) -> DT:
if isinstance(dest_type_or_obj, type):
dest_obj = dest_type_or_obj()
else:
dest_obj = dest_type_or_obj
return dest_obj
class Dest:
pass
instance_dest = tmap(Dest()) # Works fine
type_dest = tmap(Dest) # [arg-type] mypy(error)
# Argument 2 to "map" of "ObjectMapper" has incompatible type "Type[Dest]"; expected "Type[<nothing>]"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然技术上等效,但 MyPy 需要 使用
overload< /code>
:
这使得 MyPy 能够在实例和类型情况下正确推断类型变量。
While technically equivalent, MyPy requires to separate both cases using
overload
:This enables MyPy to infer the type variable properly in both the instance and type case.
您应该将
Dest
类绑定到 TypeVar,以防止Type[]
错误:You should bound the
Dest
class to TypeVar, to prevent theType[<nothing>]
error: