Mypy + flake8: Is there any way to surpress warning of `F821 undefined name`
Asked Answered
F

2

8

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

Footstall answered 4/12, 2018 at 4:41 Comment(1)
change B to 'B' works for me.....Footstall
A
4

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

Anetteaneurin answered 4/12, 2018 at 5:54 Comment(0)
G
13

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

Gabbert answered 6/4, 2019 at 15:41 Comment(0)
A
4

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

Anetteaneurin answered 4/12, 2018 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.