Scope in 2.2.1

David LeBlanc whisper at oz.net
Sat May 11 03:55:12 EDT 2002


The 2.2.1 Python doc in Appendix A1 says:
"If a name binding operation occurs anywhere within a code block, all uses
of the name within the block are treated as references to the current block.
This can lead to errors when a name is used within a block before it is
bound."

def foo():			#block
	bar = 0		#binding

bar now is a reference to foo? Somehow, I doubt that!

My other question pertaining to this paragraph is: what errors can occur if
a name is used before it's bound?

My other question is illustrated by this code:

>>> def foo():
...     bar = 0
...     bar2 = 0
...     def fee():
...             print bar
...             bar2 += 1
...             print bar2
...     fee()
...
>>> foo()
0
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 8, in foo
  File "<stdin>", line 6, in fee
UnboundLocalError: local variable 'bar2' referenced before assignment

Is the bar in "print bar" the bar of foo(), or is it an unbound bar?

Is foo.bar2 the bar2 in fee() or is it a new local fee.bar2? The traceback
implies that the "print bar" statement used foo.bar, yet it blew up on
incrementing bar2! (Note: the error reporting seems misleading, since "+="
is an assignment no?)

Damn, it's friday evening - I should BE in a bar :-)

David LeBlanc
Seattle, WA USA






More information about the Python-list mailing list