when is a != foo.a?

John Machin sjmachin at lexicon.net
Mon Aug 28 08:14:59 EDT 2006


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




More information about the Python-list mailing list