That's becouse Python automatically acts like the variable is global unless you define or try to modify it in function. Try adding global a
to your code.
>>> a = 123
>>> def f():
... global a
... print a
... a = 456
... print a
...
>>> f()
123
456
>>> a
456
In the first example you did not define and did not modify, so it was a global one. But if you would like to, for example, add 20 to a, you also have to use global a
.
Also be aware, that the a in f function is a global and it's value will differ after the run of f function.
If you want to create a local variable, then remember, that declaration always go before the reading, so print a
can not be done before a = 456
.
EDIT:
Ok, while we're talking about closures and dangerous of using global there's other possibility.
>>> a = 123
>>> def f():
... b = a
... print b
... b = 456
... print b
...
>>> f()
123
456
>>> a
123
>>>
Here we use a closure read-only ability to make a copy of a and than modify this copy, without modifing the outside a
variable AS LONG AS IT'S INTEGER. Remember, that b
keeps a reference to a
. If a
is, for example, a list and the f
operation is like b.append(3)
, then both a
and b
will be available and modified outside the scope.
The choice of method is different due to needs.