Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

python - UnboundLocalError with nested function scopes

I have code like this (simplified):

def outer():
    ctr = 0

    def inner():
        ctr += 1

    inner()

But ctr causes an error:

Traceback (most recent call last):
  File "foo.py", line 9, in <module>
    outer()
  File "foo.py", line 7, in outer
    inner()
  File "foo.py", line 5, in inner
    ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment

How can I fix this? I thought nested scopes would have allowed me to do this. I've tried with 'global', but it still doesn't work.

question from:https://stackoverflow.com/questions/65913607/scope-of-dictionaries-vs-variables-for-def-in-a-python-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're using Python 3, you can use the nonlocal statement to enable rebinding of a nonlocal name:

def outer():
    ctr = 0

    def inner():
        nonlocal ctr
        ctr += 1

    inner()

If you're using Python 2, which doesn't have nonlocal, you need to perform your incrementing without barename rebinding (by keeping the counter as an item or attribute of some barename, not as a barename itself). For example:

...
ctr = [0]

def inner():
    ctr[0] += 1
...

and of course use ctr[0] wherever you're using bare ctr now elsewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...