This is saved in my file function_local.py:
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
Output:
$ python function_local.py
x is 50
Changed local x to 2
x is still 50
Question: When we print the first line inside the Function, why does it print out 50, not 2? Even if it is said, in the function, that x = 2?
In case you assign to a variable name (that wasn't declared
globalornonlocal) in a function or use the variable name in the argument list of the function the variable name will become part of the function.In that case you could've used any variable name inside the function because it will always refer to the local variable that was passed in:
More explanation
I'm going to try to show what I meant earlier when I said that
xwith "will become part of the function".The
__code__.co_varnamesof a function holds the list of local variable names of the function. So let's see what happens in a few cases:If it's part of the signature:
If you assign to the variable (anywhere in the function):
If you only access the variable name:
In this case it will actually look up the variable name in the outer scopes because the variable name
xisn't part of the functions varnames!I can understand how this could confuse you because just by adding a
x=<whatever>anywhere in the function will make it part of the function:In that case it won't look up the variable
xfrom the outer scope because it's part of the function now and you'll get a tell-tale Exception (because even thoughxis part of the function it isn't assigned to yet):Obviously, it would work if you access it after assigning to it:
Or if you pass it in when you call the function:
Another important point about local variable names is that you can't set variables from outer scopes, except when you tell Python to explicitly not make
xpart of the local variable names, for example withglobalornonlocal:This will actually overwrite what the global (or nonlocal) variable name
xrefers to when you callfunc()!