如何注释现有对象的变量?(与mypy合作)

2024-10-03 06:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

def get_source(import_name: str) -> Optional[str]:
    spec = get_spec(import_name)
    # Now, here. The spec.loader might be one of several values.
    # But I *know* that it is gonna be importlib.machinery.SourceFileloader
    # I need to typecast the attribute of the spec.loader into the above
    if spec and spec.loader.path.endswith('.py'):
        return spec.loader.get_data(spec.loader.path).decode("utf-8")
    return None


def get_spec(import_name: str) -> importlib.machinery.ModuleSpec:
    try:
        return importlib.util.find_spec(import_name)
    except (ImportError, AttributeError, TypeError, ValueError):
        return None

显然,PEP526允许我尝试使用最基本的语法

obj.attr: annotation

然而,从Rossum's comment可以看出,类型检查器显然不必支持这种语法。mypy给出了错误Type cannot be declared in assignment to non-self attribute

现在,根据我在typeshed上的github上发现的另一个问题,您可以进行断言,让mypy知道对象所属的类型。而不是打字

assert isinstance(obj.attr, annotation)

然而,对我来说,这感觉是错误的。如果可能的话,我正在尝试使用键入功能,我正在尝试贡献的项目使用mypy作为它们的类型检查器

有效但让我恨自己的断言版本是:

def get_source(import_name: str) -> Optional[str]:
    spec = get_spec(import_name)
    assert isinstance(spec.loader, importlib.machinery.SourceFileLoader)
    assert isinstance(spec.loader.path, str)
    if spec and spec.loader.path.endswith('.py'):
        return spec.loader.get_data(spec.loader.path).decode("utf-8")
    return None

我读过的无数打字和mypy问题都没有帮助,所以我在这里


Tags: thepathnameimportnonegetreturndef