In the following code, flake8 say F821 undefined name 'B'
.
But for mypy, type hint for f
is neccesary.
How to ignore such warnings by flake8?
def f(b: B) -> None:
pass
class B():
pass
This example can be solved trivially: change the order of declarations. But sometimes I cannot change the orders in realistic cases . Such misleading warnings are noisy for me.
My env: Python 3.6 + flake8 3.6.0 + mypy 0.641 + flake8-mypy 17.8.0
This isn't a misleading warning and should not be ignored, running your code will lead to a crash currently:
$ python3.8 t.py
Traceback (most recent call last):
File "t.py", line 1, in <module>
def f(b: B) -> None:
NameError: name 'B' is not defined
You have two options to fix this, one is to explicitly use a forward declaration (by wrapping the typename in quotes):
def f(b: 'B') -> None:
pass
class B():
pass
runtime:
$ python3.8 t.py
$ flake8 t.py
Or to use from __future__ import annotations
(new in python3.7):
from __future__ import annotations
def f(b: B) -> None:
pass
class B():
pass
NOTE: I'm using flake8 3.7.x which also improved handling of forward annotations and type comments
You can use # noqa:
to silence some errors. Example:
test.py
def f(b: B) -> None: # noqa: F821
pass
class B():
pass
bash
$ flake8 test.py
(return no error)
See also: http://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html#in-line-ignoring-errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With