scope of function parameters

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 29 08:47:01 EDT 2011


On Sun, 29 May 2011 11:47:26 +0200, Wolfgang Rohdewald wrote:

> On Sonntag 29 Mai 2011, Henry Olders wrote:
>> It seems that in Python, a variable inside a function is global unless
>> it's assigned.
> 
> no, they are local

I'm afraid you are incorrect. Names inside a function are global unless 
assigned to somewhere.

>>> a = 1
>>> def f():
...     print a  # Not local, global.
...
>>> f()
1


By default, names inside a function must be treated as global, otherwise 
you couldn't easily refer to global functions:

def f(x):
    print len(x)

because len would be a local name, which doesn't exist. In Python, built-
in names are "variables" just like any other.

Python's scoping rule is something like this:

If a name is assigned to anywhere in the function, treat it as a local, 
and look it up in the local namespace. If not found, raise 
UnboundLocalError.

If a name is never assigned to, or if it is declared global, then look it 
up in the global namespace. If not found, look for it in the built-ins. 
If still not found, raise NameError.

Nested scopes (functions inside functions) make the scoping rules a 
little more complex.

If a name is a function parameter, that is equivalent to being assigned 
to inside the function.


-- 
Steven



More information about the Python-list mailing list