Dynamic package exploration

Thomas Wouters thomas at xs4all.net
Sat Jul 22 12:27:03 EDT 2000


On Sat, Jul 22, 2000 at 12:15:34AM +0000, Sebastien Pierre wrote:

> BTW, what happens if I do "import os" and then I do a "os=Thing()" and I
> do "print os.name", assuming that my Thing instance has a name="Hello"
> property ?

Assignment works differently, in Python, than in most languages. Assignment
just binds a name in the local namespace to an object. With 'import os', you
load the module 'os' (which usually is linked statically, so is already
imported) and bind it to the local name 'os'. If you then do 'os=Thing()',
you create a new Thing (or call the function Thing, if it's a function or
other callable object) and bind the resulting object to the local name 'os'
-- overwriting the previous 'os'.

> I guess it will print "Hello" ....but what is the scope of name
> resolution, something like block->function->class->module ?

'local' -> 'global'. 'global' is the top-level of the module, and 'local' is
the current function or class, or the same as 'global' if you are at the top
level.

So:

#file spam

#global:
x = 1
if x:
    y = 2

#local:
def spam(x):
    z = x
class Spam:
    _a = 1

Note that nothing is said about nested functions! You can only 'reach' the
current function, or the global namespace, so you can't actually do this:

def spam(x,y):
    def doit():
        print "spam spam spam"*x

    for i in range(y):
        doit()

Because 'x' doesn't exist in doit()'s local namespace, and it doesn't exist
in the global namespace, this'll give a nameerror. (unless 'x' does exist in
the global namespace, in which case you might get unexpected behaviour.)

Oh, there is also a magical third namespace, the 'builtin' one. It contains
all the builtin functions, and is queried last. You can't accidentily write
to it, though you can create a variable with the same in the local or global
namespace, 'shadowing' the builtin.

Tutorially-y'rs,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list