when is a != foo.a?

Chaz Ginger cginboston at hotmail.com
Mon Aug 28 08:28:38 EDT 2006


John Machin wrote:
> Chaz Ginger wrote:
>> I am somewhat new to Python (last year). As such I encounter little
>> "gotchas" all the time. I am wondering is someone can explain this to me:
>>
>> If have three simple files:
>>
>> a.py ---------------------
>>
>> foo = None
>> def a(b):
>> 	global foo
>> 	foo = b
>>
>> b.py ----------------------
>>
>> from a import foo
>> def b(): print foo
>>
>> c.py ----------------------
>>
>> import a
>> from b import b
>>
>> print 'per a.a() ',a.foo
>> a.a(245)
>> print 'expect 245 ', a.foo
>> b()
>>
>>
>> If I run 'python c.py' I get the following printed out:
>>
>>
>> per a.a()  None
>> expect 245  245
>> None
>>
>>
>> That surprised me. If I change b.py to
>>
>> import a
>> def b(): print a.foo
>>
>> I get the following (which is what I expected originally):
>>
>>
>> per a.a()  None
>> expect 245  245
>> 245
>>
>>
>> Can someone explain what is really going on here?
> 
> You are, in a very roundabout fashion, effectively executing the
> following bindings:
> 
>     a.foo = None # done when a is first imported
>     b.foo = a.foo # done in module b by "from a import foo"
>     a.foo = 245
> 
> So b.foo is bound to None, and a.foo is bound to 245. 
> 
> Cheers,
> John
> 

Thanks John. It is a lot different from the C and C++ world where you 
can hold a reference to something and use it. That is how I thought 
about what I was doing and learned it wasn't quite right! lol.

Thanks again.



More information about the Python-list mailing list