jemnotesversion 2 / featuring this entry or see all/search

May 1
This code will fail:
l = []
def app():
  l += (1,)
app()
It will fail with an UnboundLocalError. According to this website, this is because ‘If a value is assigned to a variable in a function body, the variable will be local, even if there is a global variable with the same name, and this global variable has been used before the assignment.’
This is quite different to the behaviour if you don’t try and perform an assignment, and so is a bit confusing. Of course, there are few cases where global variables are the correct tool, but sometimes they can be handy.