Closure/binding problem or misunderstanding

Bob.Sidebotham at gmail.com Bob.Sidebotham at gmail.com
Fri Nov 9 15:32:08 CET 2007


If I run the following code:

class path(object):
    def __init__(self, **subdirs):
        for name, path in subdirs.iteritems():
            def getpath():
                return path
            setattr(self, name, getpath)

export = path(
    one = 'this is one',
    two = 'this is two',
)

print "invoking", export.one, export.one()
print "invoking", export.two, export.two()

I get this output:

invoking <function getpath at 0x400ded14> this is one
invoking <function getpath at 0x400ded84> this is one

So there apparently are two definitions of the function "getpath" (the
addresses are different, anyway), but they seem to have the same value
for the binding of "path". It's not clear to me, after reading what I
can find about python name binding, whether this is the expected
behavior, or not (although I was surprised).

Can anyone enlighten me?

Thanks,
Bob Sidebotham




More information about the Python-list mailing list