标签: mypy

Python> = 3.5:在运行时检查类型注释

是否typing模块(或任何其它模块)表现出一个API来类型检查在运行时的变量,类似于isinstance()但了解中定义的类型的类typing

我想做一些类似于:

from typing import List
assert isinstance([1, 'bob'], List[int]), 'Wrong type'
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x mypy

12
推荐指数
3
解决办法
2883
查看次数

类方法返回实例的MyPy注释

我该如何注释一个@classmethod返回实例的cls?这是一个糟糕的例子:

class Foo(object):
    def __init__(self, bar: str):
        self.bar = bar

    @classmethod
    def with_stuff_appended(cls, bar: str) -> ???:
        return cls(bar + "stuff")
Run Code Online (Sandbox Code Playgroud)

这会返回一个Foo但更准确地返回Foo调用此子类的任何子类,因此使用注释-> "Foo"不够好.

python mypy

12
推荐指数
3
解决办法
3151
查看次数

Is there a way to totally ignore all of the MyPy errors in specific project packages?

Is there a way to ignore all of the errors in certain packages within my project?

Some of the code in my project is compiled Protocol Buffers code which doesn't pass a MyPy check. It all lives within a directory /myproj/generated/proto.

Here's what I have in my mypy config file:

[mypy-myproject.generated]
ignore_missing_imports = True
ignore_errors = True
Run Code Online (Sandbox Code Playgroud)

What can I add to this to make it ignore all error messages generated from an analysis of anything that's inside of myproject.generated? …

python type-hinting mypy

12
推荐指数
1
解决办法
6337
查看次数

如何让 mypy 识别较新版本的 python?

我刚刚将项目更新到 Python 3.7,当我在项目上运行 mypy 时,我看到此错误:error: "Type[datetime]" has no attribute "fromisoformat"

datetime 在 Python 3.7 中确实有这个函数fromisoformat,但在以前的 Python 版本中没有。为什么 mypy 报告此错误,如何让它正确分析 Python 3.7?

到目前为止我尝试过的事情:

  • 删除 .mypy_cache (其中有一个看起来可疑的子文件夹,标题为3.6
  • 重新安装 mypypip install --upgrade --force-reinstall mypy

重现:

  • 创建一个python 3.6项目

  • 在项目 venv 中安装 mypy 0.761(最新)

  • mypy .使用 mypy ( )扫描项目

  • 将项目更新为python 3.7

  • 添加一个包含以下代码的文件:

    from datetime import datetime
    datetime.fromisoformat('2011-11-04 00:05:23.283')
    
    Run Code Online (Sandbox Code Playgroud)
  • 再次扫描项目 ( mypy .) [更新:这实际上工作得很好。它重新运行我的预提交挂钩,而没有在新的 Python 版本 venv 上重新安装预提交,从而导致了问题。]

python python-3.x mypy python-3.7

12
推荐指数
2
解决办法
5481
查看次数

MyPy 中的相同类型如何不兼容?

使用以下示例:

from typing import Callable, Generic, Type, TypeVar

ThetaType = TypeVar('ThetaType', bound=int)
XType = TypeVar('XType', bound=int)


class IteratedFunction(Generic[ThetaType, XType]):

    def find_fixed_point(self,
                         theta: ThetaType,
                         x_init: XType) -> XType:
        return x_init


def combinator(
    iterated_function_cls: Type[
        IteratedFunction[ThetaType, XType]]) -> Callable[
            [IteratedFunction[ThetaType, XType]], XType]:
    old_find_fixed_point = iterated_function_cls.find_fixed_point

    def new_find_fixed_point(
            iterated_function: IteratedFunction[ThetaType, XType],
            theta: ThetaType,
            x_init: XType) -> XType:
        return old_find_fixed_point(iterated_function, theta, x_init)

    return new_find_fixed_point
Run Code Online (Sandbox Code Playgroud)

MyPy 说:

a.py:25: error: Incompatible return value type (got "XType", expected "XType")
a.py:25: error: Argument 1 has incompatible type "IteratedFunction[ThetaType, …
Run Code Online (Sandbox Code Playgroud)

python mypy python-typing

12
推荐指数
1
解决办法
976
查看次数

我可以告诉 mypy 表达式不会返回可选值吗?

我有以下代码:

def extract_table_date(bucket_path: str) -> str:
    event_date = re.search(r"date=([^/]+)", bucket_path)
    return event_date.group(1)[0:10].replace("-", "")
Run Code Online (Sandbox Code Playgroud)

mypy 在最后一行抛出错误:

“Optional[Match[str]]”的“None”项没有属性“group”

我想我可以通过为 分配一个类型来解决这个问题event_date,我可以:

from typing import Match

def extract_table_date(bucket_path: str) -> str:
    event_date: Match = re.search(r"date=([^/]+)", bucket_path)
    return event_date.group(1)[0:10].replace("-", "")
Run Code Online (Sandbox Code Playgroud)

但 mypy 现在在函数的第一行抛出另一个错误:

赋值中的类型不兼容(表达式的类型为“Optional[Match[Any]]”,变量的类型为“Match[Any]”)

我真的不知道如何通知 mypy 结果不是可选的,但尽管如此,我还是遵循了可选类型和 None 类型的建议,添加了断言:

from typing import Match

def extract_table_date(bucket_path: str) -> str:
    assert bucket_path is not None
    event_date: Match = re.search(r"date=([^/]+)", bucket_path)
    return event_date.group(1)[0:10].replace("-", "")
Run Code Online (Sandbox Code Playgroud)

但 mypy 仍然引发相同的错误。

我尝试通过更改定义的类型来修复event_date

from typing import Match, …
Run Code Online (Sandbox Code Playgroud)

python mypy python-typing

12
推荐指数
1
解决办法
9280
查看次数

为什么 mypy 很难分配给嵌套字典?

mypy版本0.910

考虑

d = {
    'a': 'a',
    'b': {
        'c': 1
    }
}

d['b']['d'] = 'b'
Run Code Online (Sandbox Code Playgroud)

将其提供给mypy结果

error: Unsupported target for indexed assignment ("Collection[str]")
Run Code Online (Sandbox Code Playgroud)

mypy放置推断错误类型的一侧d(它显然不是字符串集合),添加一个非常基本的显式类型d修复此问题:

d: dict = {
    ... # same as above
}
Run Code Online (Sandbox Code Playgroud)
Success: no issues found in 1 source file
Run Code Online (Sandbox Code Playgroud)

我觉得这很奇怪。mypy绝对应该能够推断出这d是一个没有d: dict.

python type-hinting mypy python-typing

12
推荐指数
1
解决办法
3016
查看次数

禁止 Mypy 注释

我从 Mypy 的表单输出中得到了大量的“注释”:

note: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs  [annotation-unchecked]
Run Code Online (Sandbox Code Playgroud)

check_untyped_defs = false即使在 my 中明确设置也pyproject.toml无济于事。

我怎样才能抑制这些注释?

python mypy

12
推荐指数
1
解决办法
3761
查看次数

用于类型提升的 Python 类型提示

考虑一个执行类型提升的函数,例如两个数字的简单乘法,两个数字都可以是intfloat

def mul(a: int | float, b: int | float):  # return type?
    return a * b
Run Code Online (Sandbox Code Playgroud)

该函数返回,但和均为 的float情况除外。abint

如何正确、简洁地注释返回类型?我知道我可以这样做@overload

from typing import overload

@overload
def mul(a: int, b: int) -> int: ...

@overload
def mul(a: float, b: int | float) -> float: ...

@overload
def mul(a: int | float, b: float) -> float: ...

def mul(a, b):
    return a * b
Run Code Online (Sandbox Code Playgroud)

但这非常冗长,并且需要许多重载来处理我想象的某些“类型函数”应该处理的事情。在 C++ 中,这可以通过SFINAE来完成。在Python中,我可以用通用函数来做类似的事情吗?

def mul(a: …
Run Code Online (Sandbox Code Playgroud)

python type-annotation mypy python-typing

12
推荐指数
0
解决办法
457
查看次数

Mypy 子类中更具体的参数

我想声明一个带有抽象方法的基类,该方法具有类型化参数,以便实现类可以为该参数指定更具体的类型,例如:

from abc import ABC, abstractmethod

class Job(ABC):
    pass

class EasyJob(Job):
    pass

class HardJob(Job):
    pass

class Worker(ABC):
    @abstractmethod
    def run(self, job: Job) -> None:
        raise NotImplementedError()

class EasyWorker(Worker):
    def run(self, job: EasyJob) -> None:
        pass

class HardWorker(Worker):
    def run(self, job: HardJob) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

然而,mypy 对此抱怨是可以理解的:

line 14: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the argument type as "Job"
line 18: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the …
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy python-typing

11
推荐指数
1
解决办法
763
查看次数