(相关但不重复:如何注释可以作为属性实现的属性?)
我想创建一个Protocol,其中的字段可以通过简单类型和属性来实现。例如:
class P(Protocol):
v: int
@dataclass
class Foo(P):
v: int
class Bar(P):
@property
def v(self) -> int: # ERROR
return
Run Code Online (Sandbox Code Playgroud)
但上面的代码没有进行类型检查。我应该如何修复它?
注意:我想解决这个问题而不重写Foo和Bar,因为Foo和Bar不是我实现的。
根据这个问题,下面的代码不是解决方案,因为只读成员property和简单成员具有细微不同的语义。
class P(Protocol):
@property
def v(self) -> int: # declare as property
...
Run Code Online (Sandbox Code Playgroud)
Protocol由于差异,皮赖特否认了这一点。
我正在使用Python 3.5和Mypy对我的脚本进行一些基本的静态检查.最近我重构了一些返回OrderedDict的方法,但是当我尝试使用指定了Key和Value类型的返回注释时,遇到了''type'对象不可订阅"错误.
减少的例子:
#!/usr/bin/env python3.5
from collections import OrderedDict
# this works
def foo() -> OrderedDict:
result = OrderedDict() # type: OrderedDict[str, int]
result['foo'] = 123
return result
# this doesn't
def foo2() -> OrderedDict[str, int]:
result = OrderedDict() # type: OrderedDict[str, int]
result['foo'] = 123
return result
print(foo())
Run Code Online (Sandbox Code Playgroud)
这是运行时的python输出:
Traceback (most recent call last):
File "./foo.py", line 12, in <module>
def foo2() -> OrderedDict[str, int]:
TypeError: 'type' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
然而,Mypy对注释中的类型注释没有任何问题,实际上如果我尝试这样做就会发出警告result[123] = 123.
是什么造成的?
如何使用Python类型提示注释上下文管理器?
import typing
@contextlib.contextmanager
def foo() -> ???:
yield
Run Code Online (Sandbox Code Playgroud)
关于contextlib的文档并未提及类型.
关于typing.ContextManager的文档也不是那么有用.
还有typing.Generator,至少有一个例子.这是否意味着我应该使用typing.Generator[None, None, None]而不是typing.ContextManager?
import typing
@contextlib.contextmanager
def foo() -> typing.Generator[None, None, None]:
yield
Run Code Online (Sandbox Code Playgroud) 当我尝试使用在另一个包中定义的装饰器时, mypy 失败并显示错误消息Untyped decorator makes function "my_method" untyped。我应该如何定义我的装饰器以确保它通过?
from mypackage import mydecorator
@mydecorator
def my_method(date: int) -> str:
...
Run Code Online (Sandbox Code Playgroud) 我有这个代码:
from pydantic import BaseModel, constr
DeptNumber = constr(min_length=6, max_length=6)
class MyStuff(BaseModel):
dept: DeptNumber
ms = MyStuff(dept = "123456")
Run Code Online (Sandbox Code Playgroud)
deptnr.py:6:错误:变量“deptnr.DeptNumber”作为类型无效
deptnr.py:6:注意:请参阅https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs -类型别名
提供的链接似乎并没有真正解决我的问题(我没有使用Type)。
不管有没有这个都会发生这种情况mypy.ini:
[mypy]
plugins = pydantic.mypy
[pydantic-mypy]
init_typed = true
Run Code Online (Sandbox Code Playgroud)
最初我在 Pydantic 中也遇到了choice如下错误,但我通过使用 Python 解决了这个问题Literal。
DIR = choice(["North", "East", "South", "West"])
Run Code Online (Sandbox Code Playgroud)
我需要改变什么才能让 mypy 对 Pydantic 感到满意constr?
以下代码无法按预期工作。显然,我不能在类定义中使用类自己的类型:
class Foo:
def __init__(self, key :str) -> None:
self.key = key
def __eq__(self, other :Foo) -> bool:
return self.key == other.key
print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))
Run Code Online (Sandbox Code Playgroud)
运行结果如下:
Traceback (most recent call last):
File "class_own_type.py", line 1, in <module>
class Foo:
File "class_own_type.py", line 5, in Foo
def __eq__(self, other :Foo) -> bool:
NameError: name 'Foo' is not defined
Run Code Online (Sandbox Code Playgroud)
此外,检查代码mypy返回:
class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype …Run Code Online (Sandbox Code Playgroud) 我已经读过,我可以通过使用一个被调用的函数来揭示变量的类型reveal_type,但我找不到如何使用它或从哪里导入它.
我在我的python项目中使用mypy进行类型检查.我也使用PyYAML来读取和编写项目配置文件.不幸的是,当使用PyYAML文档中推荐的导入机制时,这会在尝试导入本机库的try/except子句中生成虚假错误:
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
Run Code Online (Sandbox Code Playgroud)
在我的系统上CLoader并且CDumper不存在,这导致错误error: Module 'yaml' has no attribute 'CLoader'和error: Module 'yaml' has no attribute 'CDumper'.
有没有办法让mypy忽略这一行的错误?我希望我可以做这样的事情让mypy跳过这一行:
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper # nomypy
except ImportError:
from yaml import Loader, Dumper
Run Code Online (Sandbox Code Playgroud) 今天我深入研究了 Liskov 的替换原则和协方差/逆变。
我被困在以下之间的区别上:
T = TypeVar("T", bound=Union[A, B])T = TypeVar("T", A, B, covariant=True)我对#1 的理解
TypeVar('T', A, B) 和 TypeVar('T', bound=Union[A, B]) 的区别
这个答案明确指出T可以是:
Union[A, B](或任何亚型的联合A和B如Union[A, BChild])A(或 的任何子类型A)B(或 的任何子类型B)
这对我来说很有意义。
我有缺陷的理解#2
MyPy 不允许受约束的 TypeVar 是协变的?定义具有约束但协变的键值类型的通用字典
重新提及bound=Union[A, B]案例,但没有理解选项#2 的含义,A, B, covariant=True。
我试过玩弄mypy,但似乎无法弄清楚。
谁能指出这是什么意思?
我认为这意味着:
A(或 的任何子类型A)B(或 …我们目前Mypy在项目中使用(v 0.910)进行pyproject.toml配置。
我有以下文件结构:
src
--app
--generated
--service
--data
--ingest
Run Code Online (Sandbox Code Playgroud)
pyproject.toml:
...
[tool.mypy]
python_version = 3.8
disallow_untyped_defs = true
exclude = "(src/app/generated)|(src/ingest)"
...
Run Code Online (Sandbox Code Playgroud)
使用此配置运行时,src/ingest将忽略该文件夹,但不会忽略该src/app/generated文件夹。为了测试正则表达式,我还尝试了:
...
[tool.mypy]
python_version = 3.8
disallow_untyped_defs = true
exclude = "(src/app)|(src/ingest)"
...
Run Code Online (Sandbox Code Playgroud)
src
--app
--generated
--service
--data
--ingest
Run Code Online (Sandbox Code Playgroud)
成功忽略了所有文件。我想知道为什么第一个示例不忽略src/app/generated文件夹。
mypy ×10
python ×10
type-hinting ×2
covariance ×1
oop ×1
pydantic ×1
pyright ×1
python-3.5 ×1
types ×1
typing ×1