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. By using the 'TYPE_CHECKING' constant from the 'typing' module, the import statement within the type annotation block is ignored during runtime. 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 cleaner.
Despite these workarounds, using mixins with type hinting may still require restructuring to ensure that both PyCharm and mypy type checking works as expected. Mypy recommends creating an ABC from which both the main and mixin classes inherit.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3