简体   繁体   中英

Weird namespace behaviour

When trying to run the following code:

i = 0
def truc():
    print (i)
    if (False): i = 0
truc()

it yields an UnboundLocalError, but

i = 0
def truc():
    print (i)
    #if (False): i = 0
truc()

doesn't.

Is that a wanted behaviour ?

Is there a way to modify the value of a variable without creating a new one ? I could use a dict of one element. It works but it seems ugly:

i = {0 : 0}
def truc():
    print (i[0])
    if (False): i[0] = 0
truc()

Isn't it a better solution ?

just add

global i

at the beginning of the method truc() to declare that i is global variable

def truc():
    global i
    if (False):
        i = 0

Take a look at this topic in Python's FAQ to get more informations

i = 0
def truc():
    global i
    print (i)
    if (False): i = 0
truc()

To refer the outer scope variable of the function, i should be declared as global.

You'll have to add global i to the function.

i = 0
def truc():
    global i
    if (False):
        i = 0

Other ways to handle this problem is:

Making i capitalized you'll be able to access it without the global however i is then unchangeable which seems like something that isn't appropriate in your case.

Taking i as an argument. This makes the code less messy and easier to debug later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM