Ara*_*Fey 21 python generics typing
我正在尝试编写验证类型提示的代码,为了做到这一点,我必须找出注释是什么类型的对象.例如,考虑一下该片段应该告诉用户期望的值是什么类型:
import typing
typ = typing.Union[int, str]
if issubclass(typ, typing.Union):
print('value type should be one of', typ.__args__)
elif issubclass(typ, typing.Generic):
print('value type should be a structure of', typ.__args__[0])
else:
print('value type should be', typ)
Run Code Online (Sandbox Code Playgroud)
这应该打印"值类型应该是(int,str)之一",而是抛出异常:
Traceback (most recent call last):
File "untitled.py", line 6, in <module>
if issubclass(typ, typing.Union):
File "C:\Python34\lib\site-packages\typing.py", line 829, in __subclasscheck__
raise TypeError("Unions cannot be used with issubclass().")
TypeError: Unions cannot be used with issubclass().
Run Code Online (Sandbox Code Playgroud)
isinstance 也不起作用:
>>> isinstance(typ, typing.Union)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\typing.py", line 826, in __instancecheck__
raise TypeError("Unions cannot be used with isinstance().")
TypeError: Unions cannot be used with isinstance().
Run Code Online (Sandbox Code Playgroud)
什么是检查是否typ是正确的方法typing.Generic?
如果可能的话,我希望看到一个由文档或PEP或其他资源支持的解决方案.通过访问未记录的内部属性"工作"的"解决方案"很容易找到.但更有可能的是,它将成为一个实现细节,并将在未来的版本中发生变化.我正在寻找"正确的方法"来做到这一点.
sai*_*ero 27
正如sonny-garcia在评论中指出的那样,get_origin()适用于 python 3.8
import typing
from typing import get_origin
typ = typing.Union[int, str]
get_origin(typ) == typing.Union
#True
Run Code Online (Sandbox Code Playgroud)
您可以在文档中找到更多详细信息
Jac*_*din 18
您可能正在寻找__origin__:
Run Code Online (Sandbox Code Playgroud)# * __origin__ keeps a reference to a type that was subscripted, # e.g., Union[T, int].__origin__ == Union;`
import typing
typ = typing.Union[int, str]
if typ.__origin__ is typing.Union:
print('value type should be one of', typ.__args__)
elif typ.__origin__ is typing.Generic:
print('value type should be a structure of', typ.__args__[0])
else:
print('value type should be', typ)
>>>value type should be one of (<class 'int'>, <class 'str'>)
Run Code Online (Sandbox Code Playgroud)
我能找到的最好的提倡使用这个无证件的属性是Guido Van Rossum(2年前)的这个令人放心的引用:
我可以推荐的最好的方法就是使用
__origin__- 如果我们要更改此属性,仍然需要使用其他方法来访问相同的信息,并且很容易为代码发生问题__origin__.(我不太担心改变而__origin__不是__extra__.)你也可以看看内部函数_gorg()和_geqv()(这些名称不会成为任何公共API的一部分,显然,但它们的实现非常简单,在概念上很有用).
文档中的这个警告似乎表明大理石中没有任何设置:
如果核心开发人员认为有必要,可能会添加新功能,甚至可能会在次要版本之间更改API.
Ara*_*Fey 12
没有获得此信息的官方方法。该typing模块仍在大量开发中,并且没有公共API可言。(实际上,它可能永远不会有一个。)
我们所能做的就是查看模块的内部结构,并找到最简捷的方式来获取我们所需要的信息。并且由于该模块仍在开发中,其内部结构将发生变化。很多。
在python 3.5和3.6中,泛型具有一个__origin__属性,该属性持有对原始泛型基类的引用(即List[int].__origin__会是List),但是在3.7中对此进行了更改。现在,找出某物是否通用的最简单方法可能是检查其__parameters__和__args__属性。
这是一组可用于检测泛型的函数:
import typing
if hasattr(typing, '_GenericAlias'):
# python 3.7
def _is_generic(cls):
if isinstance(cls, typing._GenericAlias):
return True
if isinstance(cls, typing._SpecialForm):
return cls not in {typing.Any}
return False
def _is_base_generic(cls):
if isinstance(cls, typing._GenericAlias):
if cls.__origin__ in {typing.Generic, typing._Protocol}:
return False
if isinstance(cls, typing._VariadicGenericAlias):
return True
return len(cls.__parameters__) > 0
if isinstance(cls, typing._SpecialForm):
return cls._name in {'ClassVar', 'Union', 'Optional'}
return False
else:
# python <3.7
if hasattr(typing, '_Union'):
# python 3.6
def _is_generic(cls):
if isinstance(cls, (typing.GenericMeta, typing._Union, typing._Optional, typing._ClassVar)):
return True
return False
def _is_base_generic(cls):
if isinstance(cls, (typing.GenericMeta, typing._Union)):
return cls.__args__ in {None, ()}
if isinstance(cls, typing._Optional):
return True
return False
else:
# python 3.5
def _is_generic(cls):
if isinstance(cls, (typing.GenericMeta, typing.UnionMeta, typing.OptionalMeta, typing.CallableMeta, typing.TupleMeta)):
return True
return False
def _is_base_generic(cls):
if isinstance(cls, typing.GenericMeta):
return all(isinstance(arg, typing.TypeVar) for arg in cls.__parameters__)
if isinstance(cls, typing.UnionMeta):
return cls.__union_params__ is None
if isinstance(cls, typing.TupleMeta):
return cls.__tuple_params__ is None
if isinstance(cls, typing.CallableMeta):
return cls.__args__ is None
if isinstance(cls, typing.OptionalMeta):
return True
return False
def is_generic(cls):
"""
Detects any kind of generic, for example `List` or `List[int]`. This includes "special" types like
Union and Tuple - anything that's subscriptable, basically.
"""
return _is_generic(cls)
def is_base_generic(cls):
"""
Detects generic base classes, for example `List` (but not `List[int]`)
"""
return _is_base_generic(cls)
def is_qualified_generic(cls):
"""
Detects generics with arguments, for example `List[int]` (but not `List`)
"""
return is_generic(cls) and not is_base_generic(cls)
Run Code Online (Sandbox Code Playgroud)
所有这些功能都应在所有<= 3.7的python版本中起作用(包括使用typing模块反向移植的所有<3.5版本)。
| 归档时间: |
|
| 查看次数: |
2683 次 |
| 最近记录: |