On 7/14/2010 12:06 PM, Ethan Furman wrote:

... Have you tried this?

--> def foo():
... print locals()
... blah = 'interesting'
... print locals()
...
--> foo()
{}
{'blah': 'interesting'}

As can be clearly seen, blah does not exist before the assignment -- the
*name* blah has not been *bound* to an object yet, which is also what
the error message says when you try to use it before it exists:

As already cited, according to Section 4.1 "Naming and binding" in the Language Reference, the name "blah" *does* exist before the assignment. That's the implication of this phrase:

  If the name refers to a local variable that has not been bound,

(BTW, "has not been bound" should really be "is not currently bound", to allow for use of *del* earlier in the block.)

Try this:

#--------------
def foo():
    print "1. varnames:", globals()['foo'].__code__.co_varnames
    print "2. locals:", locals()
    blah = 'interesting'
    print "3. locals:", locals()

foo()
#--------------

The output (Python 2.6.5) is:

1. varnames: ('blah',)
2. locals: {}
3. locals: {'blah': 'interesting'}

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

Reply via email to