Scope of instantiated class

Alex Martelli aleax at aleax.it
Sun Jul 21 13:51:07 EDT 2002


Peter Hansen wrote:
        ...
> When you create an object ("instantiate a class") you
> must bind it to a name ("assign it to a variable").  If

Normally, yes, but not always.

For example, class dispatcher in module asyncore of the
standard Python library does not follow this usage mode.

Rather, each instance of dispatcher (or a subclass)
registers itself in the "socket map", from which asyncore's
event loop later decides which callbacks to make as network
events happen.

Therefore, you often don't bind instances of dispatcher
(or rather subclasses thereof) to any name at the time
you instantiate them.  You just instantiate them and rely
on them to enregister so they'll stay alive exactly as
long as they need to (such instances remove themselves
from the map when they're closed).

> the name you use is local to the function, then when
> the function exits the binding is removed and the object,
> if no other names are by now bound to it, is destroyed.

Yes, except that 'names' must be used in a very wide
sense here -- e.g., async.dispatcher instances are kept
alive by references to them in the socket_map dict,
which are "names" only in a very wide sense.


More generally: the idiom of a class whose instances
automatically enregister themselves somewhere (so the
registration itself will keep them alive) is quite
important.  Tkinter widgets do that, too.  Just making
sure the _usual_ case (which is the one you describe)
isn't confused (by some newbie reader -- I'm sure you
don't personally need this reminder, Peter!) with a
law of nature:-).


Alex




More information about the Python-list mailing list