Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 855
nomaddo Avatar asked Dec 04 '18 04:12

nomaddo


2 Answers

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

like image 191
Anthony Sottile Avatar answered Oct 02 '22 15:10

Anthony Sottile


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

like image 26
takanakahiko Avatar answered Oct 02 '22 15:10

takanakahiko