Python Idioms?

Tim Peters tim.one at home.com
Tue Jun 19 03:44:35 CEST 2001


[David Stanek]
> In reading through the Python source code I came across some oddities.
> In some modules, specifically threading, the instance objects are
> created using a kind of factory method.
> e.g.
> class _X:
>     pass
>
> def X(*tupArgs, **dicArgs):
>     return apply(_X, tupArgs, dicArgs)
>
> When the class could just as easily been named X.  Is there an
> advantage to doing things this way?

This is a trick Guido uses simply to make sure you can't subclass X.  The
threading.py classes in particular *may* someday grow more-efficient
platform-specific implementations, and by playing this trick now Guido
ensures that he doesn't have to compromise on speed later by needing to
continue supplying a class.  The only real example of that now is
threading.Lock, whose definition is simply (chasing it down):

Lock = thread.allocate_lock

So Lock maps directly to a C function now; RLock and Condition etc may also
someday, but we couldn't make that change if code relied on subclassing from
RLock and Condition etc.

> Also I noticed in the same module:
> import sys
> _sys = sys
> del sys
>
> What does this do?  You still have a reference to the module.  What
> difference does it make what the name is.

Module-level names with a leading underscore are ignored by "import *".  So
this is for people using "from threading import *":  they won't pollute
their own namespace with _sys, but *would* pollute it with "sys" if the
rename weren't done.

Since threading.py was written, a better way to spell this was introduced:

import sys as _sys

BTW, in this particular case, there's a comment right in the module:

# Rename some stuff so "from threading import *" is safe





More information about the Python-list mailing list