Python Type Hinting without Cyclic Imports
Problem:
Importing modules with cyclic dependencies introduces runtime exceptions when type hinting is used in conjunction with mixin classes.
Details:
In Python 3.4, a class is split into two files (main.py and mymixin.py), where mymixin.py contains a mixin class that inherits from the main class in main.py (i.e., class Main(object, MyMixin):). Type hinting in MyMixin's methods requires specifying the return type as 'Main', leading to a cyclic import issue.
Python 3.4 Solution:
To bypass the cyclic import while type hinting, a custom approach using a forward declaration is employed.通过使用“键入”模块的“ type_checking”常数,在运行时忽略了类型注释块中的导入语句。 The 'Main' type annotation is also converted into a string to forward declare it.
Python 3.7 Solution (PEP 563):
Using the 'from future import annotations' import statement, all type annotations become strings and are skipped during runtime evaluation, making the forward declaration syntax清洁剂。
尽管有这些解决方法,但使用带有类型提示的Mixins仍需要重组以确保Pycharm和Mypy类型都可以按预期进行检查。 Mypy建议创建一个ABC,主要和Mixin类也从中继承。免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3