On 7/12/2010 4:48 AM, bart.c wrote:

>>> def foo():
print("Before:", locals())
x = 0
print("After:", locals())


>>> foo()
Before: {}
After: {'x': 0}

That's interesting. So in Python, you can't tell what local variables a
function has just by looking at it's code:

You are being fooled by the multiple meanings of the overloaded term 'variable'. Thing are clearer with the two terms 'name' and 'namespace' (a set of name-object bindings).

Before compiling function code, an interpreter must read it and make a classified list of *names*. The interpreter has to know the fixed set of local names in order to know what to do with assignment statements. If the interpreter can tell how many local names there are, so can you.

Before a function begins execution, all parameter names must be bound, with no arguments left over. At that point, the local namespace consists of those parameter-object bindings. During the execution of the function, bindings may be added and deleted. The size of the local namespace varies.

def foo(day):
if day=="Tuesday":
x=0
print ("Locals:",locals())

#foo("Monday")

Does foo() have 1 or 2 locals?

foo has 2 local names. Its local namespace starts with 1 binding and may get another, depending of the value of the first.

If the size of the local namespace at some point of execution depends on unknown information, then of course the size at that point is also unknown.

Here is another example:

>>> def f(a):
        print(locals())
        del a
        print(locals())
        a = None
        print(locals())
        
>>> f(2)
{'a': 2}
{}
{'a': None}

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to