This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: UnboundLocalError raised on call to global
Type: behavior Stage: resolved
Components: Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: camshaka, eric.smith, tim.peters
Priority: normal Keywords:

Created on 2018-07-31 10:51 by camshaka, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg322755 - (view) Author: Camille (camshaka) Date: 2018-07-31 10:51
In the following code :

def g():
    return 0

def f():
    g = g()

f()

The call to g in f fails due to an UnboundLocalError, while I expected the assignment to hide the global definition of g. Note that if it is done in two subsequent calls, i.e. with :
def f():
    goo = g()
    g = 0

The first assignment still fails.
msg322758 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-07-31 11:35
Python thinks that `g` inside `f()` is a local variable. See https://stackoverflow.com/questions/9264763/unboundlocalerror-in-python#9264845 for an explanation.

This is working as intended.
msg322779 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2018-07-31 14:13
Yes, the assignment does "hide the global definition of g".  But this determination is made at compile time, not at run time:  an assignment to `g` _anywhere_ inside `f()` makes _every_ appearance of `g` within `f()` local to `f`.
History
Date User Action Args
2022-04-11 14:59:04adminsetgithub: 78472
2018-07-31 14:13:13tim.peterssetnosy: + tim.peters
messages: + msg322779
2018-07-31 11:35:52eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg322758

resolution: not a bug
stage: resolved
2018-07-31 10:51:35camshakacreate