Python Idioms?

David Bolen db3l at fitlinxx.com
Tue Jun 19 04:56:57 CEST 2001


"David Stanek" <no_spam..python at dstanek.com-NOSPAM> writes:

> 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?
> 
> 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.

Although it's rare, the threading module is one that has been designed
to be friendly in a "from threading import *" mode.  My guess at the
rationale was a combination of the long module name, but also that the
module provides a number of threading primitives that are likely to be
heavily used within threading code.

When you use "from <module> import *" the import mechanism will
automatically skip over any entries in the module dictionary that
start with "_".  So the threading module is conscientious about what
names it leaves in its module dictionary that don't start with "_" to
avoid polluting the importers namespace.

I'm not entirely sure about how the choice between module-level
factory functions and classes were made (for example, Thread is a
straight class), but one guess I'd made is that this helps prevent
subclassing of the basic primitives - at least not without violating
the "private" nature of the "_" classes.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list