【问题标题】:Unpack Optional type annotation in Python 3.5.2在 Python 3.5.2 中解压可选类型注解
【发布时间】:2018-02-22 04:51:56
【问题描述】:

举个例子:

import typing

def foo(bar: int = None):
    pass

typing.get_type_hints(foo)

bar 的类型提示是 typing.Union[int, None]。我如何从中获得int__args____parameters__ 属性似乎都不适用于 Python 3.5.2。


更具体地说,我正在尝试编写一个通用装饰器来检查函数的签名并对参数执行特定的操作。为此,它需要从 Optional[T] 等注释中获取类,然后使用 T

annot = typing.Optional[T]
cls = # MAGIC?!
assert cls is T

【问题讨论】:

  • 看来您正在寻找annot.__args__[0](至少在3.6.1 中)。你使用的是什么 Python 版本? typing 仍然是 provisional,因此可能仍会进行更改。
  • 现在需要在 3.5 上工作。
  • 你在用3.5.2我猜?在3.5.1 中,我认为__args__ 被命名为__parameters__,所以请注意这一点(typing 模块的内部API 非常不稳定。)
  • 对了,我也回答过类似的问题:stackoverflow.com/questions/38703556/…
  • 对,我只是用不同的版本来探索它,确实存在一些差异......

标签: python python-3.x annotations type-hinting


【解决方案1】:

3.5.2 中,要获取Union 的参数,您必须使用__union_params__

>>> from typing import Union
>>> d = Union[int, str]
>>> print(*d.__union_params__)
<class 'int'> <class 'str'>

不幸的是,这似乎适用于3.5.2,它在3.5.3 中更改为使用__args__

>>> from typing import Union
>>> t = Union[int, str]
>>> t.__union_params__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_Union' object has no attribute '__union_params__'
>>> print(*t.__args__)
<class 'int'> <class 'str'>

并在以后的版本中保持__args__3.63.7)。

这是由于打字模块的临时状态。内部 API 的许多方面都在不同微版本之间发生变化,因此您可能必须处理很多晦涩的变化。

【讨论】:

    【解决方案2】:

    在这些情况下,我更愿意简单地咨询实现。在 3.5.2 中,这是 __repr__ of Union:

    def __repr__(self):
        r = super().__repr__()
        if self.__union_params__:
            r += '[%s]' % (', '.join(_type_repr(t)
                                     for t in self.__union_params__))
        return r
    

    这表明该类存储在__union_params__ 属性中:

    typing.get_type_hints(foo)['bar'].__union_params__[0] is T
    

    然而,这在 3.5.3 的 the commit 5fc25a873cfdec27e46f71e62c9b65df5667c1b4 中更改为 __args__

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多