Python type hints with imported class methods

若如初见. 提交于 2020-08-10 19:53:45

问题


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:


  1. Fix the circular import by using the typing.TYPE_CHECKING flag to import C only during type checking.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!