问题
In order to split a large class into multiple files, this answer, recommends using the import
command at the class
level to load methods whose definitions can be moved to other modules. As a minimal example,
class_def.py
:
class C:
from _methods import m
_methods.py
:
def m(self):
return "hello"
Normally, most IDEs which feature code completion will recognize functions which are defined in some class as bound methods, and self
will automatically be recognized as having the type of the class where the method was defined. Unfortunately, in the above situation, I have not defined m
inside of a class. It is impossible to tell from looking at just _methods.py
that self
should have type C
.
In the definition of m
, if I insert a line which starts with self.
, my IDE cannot suggest m
or any other methods which I might have implemented in C
.
The obvious solution would be to add a type hint:
from class_def import C
def m(self: C):
return "hello"
But now we have a circular import: the definition of C
imports _methods
, but _methods
imports C
. How can I create a type hint without introducing a circular import?
I am currently using Python 3.7, but I would also be interested in solutions requiring later versions.
回答1:
Fix the circular import by using the
typing.TYPE_CHECKING
flag to importC
only during type checking.This leaves the value of
C
undefined at runtime. Either enclose it in quotes ("C"
) or import__future__.annotations
:
_methods.py
variant 1:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from class_def import C
def m(self: "C"):
return "hello"
_methods.py
variant 2:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from class_def import C
def m(self: C):
return "hello"
来源:https://stackoverflow.com/questions/63234592/python-type-hints-with-imported-class-methods