Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python 3.x - local variable referenced before assignment (list)

I encountered an interesting error. When defining a list outside the scope of a function, like below, it causes an error: UnboundLocalError: local variable 'a' referenced before assignment

def main():
    a = []
    
    def sub():
        a += ["hello"]
        return a 
    sub()
main()

However, with the same logic, if used a.append no error is raised

def main():
    a = []
    
    def sub():
        a.append("hello")
        return a 
    sub()
main()

Is there any reason for this?

Thanks

question from:https://stackoverflow.com/questions/65861664/local-variable-referenced-before-assignment-list

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

1 Answer

0 votes
by (71.8m points)

You have to use the nonlocal keyword in this case.
nonlocal documentation

def main():
    a = []
    
    def sub():
        nonlocal a
        a += ["hello"]
        return a 
    sub()
main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...