比较Python类型的类型

2024-10-02 22:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数接受另一个用类型提示(__annotations__)注释的Python函数。我想使用这些提示在运行时进行一些类型检查。问题是来自typing module的类型类似乎不太容易使用(没有isinstance,没有issubclass)。所以,我想知道,有没有一种方法可以将它们转换为mypy类型对象,然后使用mypy.subtypes.is_subtype来比较类型提示中的类型?


Tags: 对象方法函数typing类型isisinstanceannotations
1条回答
网友
1楼 · 发布于 2024-10-02 22:29:50

答案很简单,那就是没有简单的方法。^{cd1>}模块按设计,不会为运行时检查提供太多帮助。PEP 484说

This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.

Of these goals, static analysis is the most important. This includes support for off-line type checkers such as mypy, as well as providing a standard notation that can be used by IDEs for code completion and refactoring.

Non-goals

While the proposed typing module will contain some building blocks for runtime type checking in particular the get_type_hints() function third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.

相关问题 更多 >