PyCharm 无法推断 @cache-d 方法的返回类型

问题描述 投票:0回答:1

PyCharm 的类型检查器可以很好地解决这个问题:

from functools import cache

class MyType:
  pass

@cache
def f() -> MyType:
  ...

v = f()  # v: MyType

...但不是这个:

class C:

  @cache
  def m(self) -> MyType:
    ...

v = C().m()  # v: Any

我应该怎样做才能获得良好的自动完成功能?

python pycharm type-hinting
1个回答
0
投票

这是 YouTrack/PY-49635(截至 2023 年 11 月开放)。

我当前的解决方法如下:

from functools import cache
from typing import TypeVar

if TYPE_CHECKING:
  # To be read by mypy and other proper typecheckers

  _cache = cache

else:
  # To be read by PyCharm
  # This is not actually type-safe since T is unbounded, but whatever.

  T = TypeVar('T')

  def _cache(function: T) -> T:
    '''
    Workaround for `PY-49635\
    <https://youtrack.jetbrains.com/issue/PY-49635>`_.
        
    :param function: A callable.
    :return: The same callable, wrapped in :func:`functools.cache`.
    '''
        
    return cache(function)

用途:

def f() -> YourType:
  ...

class C:

  @_cache
  def m(self) -> YourType:
    ...

v = f()      # v: YourType
v = C().m()  # v: YourType

上述解决方法适用于 PyCharm 2023.2.5。我没有测试过其他版本。

© www.soinside.com 2019 - 2024. All rights reserved.