Home  >  Article  >  Backend Development  >  How to Avoid Cyclic Imports in Python\'s Type Hinting?

How to Avoid Cyclic Imports in Python\'s Type Hinting?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 13:34:02203browse

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:

  • Mypy may require creating an abstract base class (ABC) inherited by both Main and MyMixin to ensure proper type checking.
  • PyCharm's checker may also require a similar approach for maximum compatibility.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn