You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:38:45