Home >Backend Development >Python Tutorial >How to Avoid Cyclic Imports in Python\'s Type Hinting?
Type Hinting in Python Without Cyclic Imports
Problem:
When splitting a large class into multiple files, cyclic imports can prevent type hinting from working properly. Specifically, importing the "main" class in a mixin class creates a circular dependency that hinders type checking.
Solution:
For Python 3.4:
Use the following code structure:
<code class="python"># main.py import mymixin.py class Main(object, MyMixin): def func1(self, xxx): ... # mymixin.py from typing import TYPE_CHECKING if TYPE_CHECKING: from main import Main class MyMixin(object): def func2(self: 'Main', xxx): # Note the string type hint ...</code>
The TYPE_CHECKING constant ensures that the import of main.py is only evaluated during type checking, avoiding the cyclic import error.
For Python 3.7 :
Python 3.7 introduces a more elegant solution:
<code class="python"># main.py import mymixin.py class Main(object, MyMixin): def func1(self, xxx): ... # mymixin.py from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from main import Main class MyMixin(object): def func2(self: Main, xxx): # No need for a string type hint ...</code>
The future import annotations import enables string type hints and avoids evaluating them at runtime.
Additional Considerations:
The above is the detailed content of How to Avoid Cyclic Imports in Python\'s Type Hinting?. For more information, please follow other related articles on the PHP Chinese website!