Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to modify a global int, but can modify a list. How?

Tags:

python

LISTL = [] VAR1 = 0 def foo(): ... VAR1 += 1 ... return VAR1 ...

On calling foo(), I get this error:

UnboundLocalError: local variable 'VAR1' referenced before assignment

However, consider the list LISTL

>>> def foo(x):
...     LISTL.append(x)
...     return LISTL
... 
>>> foo(5)
[5]

This works as expected. The question is why the append on a list works but I can't change the int?

Also, is this the right way to declare a global in Python? (Right after the import statements)

like image 793
user225312 Avatar asked Jan 21 '23 19:01

user225312


2 Answers

The reason for this difference has to do with how Python namespaces the names. If you're inside a function definition (def foo():), and you ACCESS a name (VAR1 or LISTL), it will first search your local namespace, where it will find nothing, and then it will search the namespace of the module the function was defined in, all the way up to the global namespace until it finds a match, or fails.

However, ACCESSING a name, and ASSIGNING a name, are two different concepts. If you're again within your function definition, and you say VAR1 = 2, you're declaring a new variable with the new local name VAR1 inside the function. This makes sense if you consider that otherwise you would encounter all sorts of naming collisions if there was no such namespacing at work.

When you append to a list, you are merely ACCESSING the list, and then calling a method on it which happens to change its conceptual value. When you use do +=, you're actually ASSIGNING a value to a name.

If you would like to be able to assign values to names defined outside of the current namespace, you can use the global keyword. In that case, within your function, you would first say global VAR1, and from there the name VAR1 would be the name in the outer namespace, and any assignments to it would take effect outside of the function.

like image 200
Joseph Spiros Avatar answered Jan 29 '23 03:01

Joseph Spiros


If you assign to a variable within a function, that variable is assumed to be local unless you declare it global.

like image 26
dan04 Avatar answered Jan 29 '23 02:01

dan04