【问题标题】:Is issubclass broken for comparing with typing.Generic in Python 3.5?与 Python 3.5 中的 typing.Generic 相比,issubclass 是否被破坏?
【发布时间】:2016-11-01 13:16:06
【问题描述】:

如何确定给定类是否是任何typing.Generic 的子类?调用issubclass 似乎没有像我预期的那样工作:

import typing

T = typing.TypeVar('T')

class A(typing.Generic[T]):
    pass

class B:
    pass

issubclass(A, typing.Generic)
>>> True

issubclass(B, typing.Generic)
>>> Traceback (most recent call last):
... <more traceback lines here>
File "<some_path>\env\lib\abc.py", line 225, in __subclasscheck__
    for scls in cls.__subclasses__():
TypeError: descriptor '__subclasses__' of 'type' object needs an argument

另外,我是否遗漏了什么,这是预期的行为还是错误?

那么,假设如果TypeError 被引发,那么它不是typing.Generic 的子类是否安全?

我正在使用 Python 3.5.2。

谢谢。

【问题讨论】:

  • 应该是issubclass(B, typing.Generic[T])
  • 它有效,是的,但仅在这种情况下,因为泛型可以提供多个类型参数。

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


【解决方案1】:

这是预期的行为(至少目前是这样)。您不能将类型提示上下文中指定的类型与类混合。您可以将type 视为标签,表示可能的类型检查器。类是您与之交互的运行时对象。

更多关于打字模块的信息可以在thread on the issue tracker 中找到(具体请查看this 帖子)。

仅作记录,typing 仍然是临时的,在它被认为稳定之前,可能会发生许多错误和许多更改,他们仍在对其进行调整,并且没有任何保证。例如,在Python 3.5.1 中,您的代码在没有任何TypeErrors 的情况下运行顺利(根据我的收集,它们是在3.5.2 中引入的):

issubclass(A, typing.Generic)
Out[28]: True

issubclass(B, typing.Generic)
Out[31]: False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 2020-04-30
    • 2018-02-26
    • 2016-07-11
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2019-06-15
    相关资源
    最近更新 更多