我有这个pyi
文件。
from __future__ import annotations
import datetime
class Payment:
amount: float = ...
date: datetime.date = ...
def set_amount(self: Payment, amount: float = Amounts.Null):
...
def get_amount(self: Payment) -> float:
...
def get_date(self: Payment) -> datetime.date:
...
class Amounts:
Null: float = ...
使用from __future__ import annotations
有助于删除self
参数的F821 undefined name 'Payment'
警告。
然而,flake8仍然显示F821 undefined name 'Amounts'
。可以以某种方式修复此警告吗(不完全禁用F821(?或者这可能是一个bug?
注意,我在Python 3.10.0
上使用flake8 4.0.1 (mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0)
。
错误没有错:
$ python3 t.pyi
Traceback (most recent call last):
File "t.pyi", line 5, in <module>
class Payment:
File "t.pyi", line 9, in Payment
def set_amount(self: Payment, amount: float = Amounts.Null):
NameError: name 'Amounts' is not defined
__future__
annotations
推迟注释,但您稍后在文件中有一个引用类的默认值(它不是注释!(
一种选择是简单的重新排序:
from __future__ import annotations
import datetime
class Amounts:
Null: float = ...
class Payment:
amount: float = ...
date: datetime.date = ...
def set_amount(self: Payment, amount: float = Amounts.Null):
...
# ...
更好的是完全省略默认值,因为它在pyi(或存根函数(中什么都不做:
from __future__ import annotations
import datetime
class Payment:
amount: float = ...
date: datetime.date = ...
def set_amount(self: Payment, amount: float = ...):
# ...
还要注意,您的函数有点不正确——现在类型检查器会将set_amount
解释为-> Any
,因为您省略了返回值,正确的做法是-> None
您可以采取的另一种方法是通过# noqa
、per-file-ignores
或其他方式忽略错误——尽管这可能不是您想要做的,因为代码已损坏
免责声明:我目前维护flake8