baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Alastair Thompson
I am completely baffled by the behavior of this code with regards to the
evaluation order of namespaces when assigning the class attributes.  Both
classes are nested within a function I called whywhywhy.

I assumed that example1 and example2 classes would look first at their own
namespace, then object, then the whywhywhy func namespace then global, and
maybe module.  It seems this is not the case.

def whywhywhy(first, second, third):
def print_stuff():
print("func: first=", first)
print("func: second=", second)
print("func: third=", third)
print_stuff()

class example1(object):
print("1cls: first=", first)
print("1cls: second=", second)
print("1cls: third=", third)

second = second
foo = third

class example2(object):
print("2cls: first=", first)
print("2cls: second=", second)
print("2cls: third=", third)

second = second
third = third

def second():
pass

whywhywhy(1,2,3)


The code above produces the following output
"""
func: first= 1
func: second= 2
func: third= 3
1cls: first= 1
1cls: second= 
1cls: third= 3
2cls: first= 1
2cls: second= 
Traceback (most recent call last):
  File "error.py", line 29, in 
whywhywhy(1,2,3)
  File "error.py", line 18, in whywhywhy
class example2(object):
  File "error.py", line 21, in example2
print("2cls: third=", third)
NameError: name 'third' is not defined
"""

In particular:

print_stuff behaves as I would expect
1cls: second #<--- Why does this look at the global namespace for second
and not the whywhywhy func namespace first.
2cls: second #<--- Why can this no longer find third, it surely hasn't hit
the line third=third

Thanks for any help you can provide. :)
Alastair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Alastair Thompson
Thats a good pointer to what is going on. Thank you Bas.

I am familiar with error such as

x=1
def foo():
x = 2
def erm():
print(x)
x=3
erm()
foo()
UnboundLocalError: local variable 'x' referenced before assignment.

It seems a bit different for classes (below), as it jumps out to get the
value from the global name space, where it didn't for functions (above).

x=1
def foo():
x = 2
class erm():
print(x)
x = 3
foo()  # This evaluates == 1

But you certainly have explained why  "NameError: name 'third' is not
defined" occurs.
-- 
http://mail.python.org/mailman/listinfo/python-list