[Tutor] PyMOTW: difflib

Kent Johnson kent37 at tds.net
Mon Apr 7 21:33:45 CEST 2008


Alan Gauld wrote:
> "Dick Moores" <rdm at rcblue.com> wrote 

>> Is a name the same as anything defined? 
> 
> Yes pretty much anything that has a name.
> 
> Its worth spending the time reading and playing with 
> this because its a fundamental concept in Python 
> and once understood many of the seeming anomolies 
> become clear.

Yes, I strongly agree. There is a bit of an aha moment when you realize, 
"oh, they are all just names in namespaces."

> I tend to think of it this way. Python does most things 
> using dictionaries. The names we define in our code 
> are merely keys into some semi-hidden dictionaries.
> The values of the dictionaries are the things the names 
> reference - values, classes, functions etc

Nitpick: I think of it that way too but it is not always correct. Many 
names are stored as key/value pairs in dicts but local variables are 
stored in a pre-allocated array and accessed by offset. There are 
probably other exceptions also. For example:

In [13]: import dis
In [15]: def foo():
    ....:     a = 10
In [16]: dis.dis(foo)
   2           0 LOAD_CONST               1 (10)
               3 STORE_FAST               0 (a)
               6 LOAD_CONST               0 (None)
               9 RETURN_VALUE

The STORE_FAST instruction is storing the (reference to) the value 10 at 
offset 0 in the local storage section of the stack frame.

> When you import a module (import x) you reference the 
> module dictionary so still need to derefence it (eg. sys.exit)
> When you import from a module (from x import *) you 
> copy the keys into your local dictionary so you don't 
> need to dereference them.
> 
> That's almost certainly not a technically correct explanation 
> of how importing really works but its conceptually how I 
> think about it. :-)

My take on this:

When you import a module, you bind a name in the current namespace to 
the module object. So
   import x
binds the name 'x' to the module object. Attributes of the module - any 
names at global scope in the module - are available using normal 
attribute access syntax, e.g.
   x.a

You can also import module x and bind it to a different name, e.g.
   import x as xx

When you import specific attributes of a module, then the value of the 
module attribute is bound to a name in the current namespace. For example
   from x import a
binds x.a to the name a. Here again, you can use a different name:
   from x import a as b
binds x.a to the name b.

   from x import *
is similar except every public attribute of x is bound to a local name.

HTH someone!
Kent


More information about the Tutor mailing list