mypy icon indicating copy to clipboard operation
mypy copied to clipboard

mypy gives 'not defined' error for use after global declaration

Open onlined opened this issue 7 years ago • 2 comments

In version 0.630 and master (with Python 3.7.0), I get this error :

def foo() -> None:
    global myglobal
    myglobal = 2  # error: Name 'myglobal' is not defined

I thought that I should not get an error. Is this behavior correct?

onlined avatar Oct 04 '18 06:10 onlined

Mypy doesn't behave correctly, but it may be somewhat difficult to fix in mypy. As a workaround, you can declare the global at module top level:

myglobal: int

def foo() -> None:
    global myglobal
    myglobal = 2  # OK

JukkaL avatar Oct 04 '18 10:10 JukkaL

Mypy doesn't behave correctly, but it may be somewhat difficult to fix in mypy. As a workaround, you can declare the global at module top level:

myglobal: int

def foo() -> None:
    global myglobal
    myglobal = 2  # OK

Looks like you don't need global myglobal with this.

raffaem avatar Sep 21 '22 08:09 raffaem