[Tutor] globals( ) and binding doubt (newbie) !

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 8 Jan 2002 17:14:49 +0100


On  0, Karthik Gurumurthy <karthikg@aztec.soft.net> wrote:

Hi! It looks like you are having fun, a newbie playing around with changing
lists of functions - welcome to Python :-)

(snip)
> >>> seq = [f1,f2,f3]     				##### I had to re-initialize the list with the
> same names again.
(snip)


> Can someone tell me why it did'nt use the correct versions of the functions
> earlier.
> When python comes across a name, it does look up in locals() or globals()
> and then executes the
> one mapped there?
(snip)

> When i redefined f1 , f2 and f3, globals would have accepted these and
> overwritten the earlier one?

When you do


def f1:
    pass
    
The name 'f1' refers to a function object.

After that, you do:

seq = [f1]

At the moment this assignment happens, the name 'f1' is looked up. 'seq' now
refers to a list object, with one element in it, a reference to the
function.* It doesn't hold the name, it holds the reference!*

Now you do

def f1:
   print "Whee!"

Now 'f1' refers to the new function. But 'seq' wasn't changed, so it still
holds the same reference as before, which refers to the old function. See?

So therefore

seq[0]()

will still print nothing, until you do seq=[f1] again.

Hope it's clearer now.

Main thing to remember in Python: everything is a reference.

-- 
Remco Gerlich