类型检查时中断导入周期

Break import cycle while type checking

我已将大型 class 实现拆分为不同的包 [1],并在方法体内使用导入以避免编译循环,如下所示:

# model.py

class MyInt:
  def __init__(self, value: int):
    self.value = value

  def is_prime(self) -> bool:
    from methods import is_prime
    return is_prime(self)
# methods.py

from model import MyInt

def is_prime(x: MyInt) -> bool:
  # TODO: actually implement this
  return x.value == 2 or x.value % 2 == 1

但是pytype对此并不满意,在到达导入周期时找不到pyi文件:

File "/home/bkim/Projects/mwe/model.py", line 6, in is_prime: Couldn't import pyi for 'methods' [pyi-error]

Can't find pyi for 'model', referenced from 'methods'

如何避免这种情况并仍然进行类型检查?

[1] 事实上,我只用了一个很小的实用方法就完成了这项工作。无需大喊大叫将 class 拆分成多个包。

此解决方案使用 typing.TYPE_CHECKING,在类型检查期间有一种行为,在运行时有另一种行为:

import typing

class MyInt:
  def is_prime(self) -> bool:
    if typing.TYPE_CHECKING:
      return False  
    from methods import is_prime
    return is_prime(self)

奇怪的是,使用 from typing import TYPE_CHECKING 不起作用,这可能是一个错误?