Python 2.7子类使用存根文件实现类型提示的问题
Hey, I’ve run into this exact issue with Python 2.7 type hints using stub files per PEP 484—subclass method signatures don’t inherit parent class type hints properly, and type checkers can’t infer the parameter types as expected.
Here’s a concrete example to illustrate the problem:
Parent class stub file a.pyi:
class A(object): def foo(self, timestamp: float): ...
Subclass in Python 2.7 file b.py:
class B(A): def foo(self, timestamp): print(timestamp) # The inferred type of timestamp is *not float*!
I tested this in PyCharm 2017.3.3, and it fails to recognize that timestamp should be a float. I haven’t verified how mypy handles this scenario yet.
Unfortunately, the only workarounds I’ve found so far both introduce code redundancy (so they’re not ideal solutions):
Workaround 1: Add a stub file for the subclass
Create a b.pyi stub file and explicitly redefine the method with the type hint:
class B(A): def foo(self, timestamp: float): ...
Workaround 2: Add inline type comments in the Python 2.7 file
Include type hints directly as comments in the subclass method definition in b.py:
class B(A): def foo(self, timestamp): # type: (float) -> None print(timestamp)
Content sourced from Stack Exchange, question author: Wolfgang Kuehn

