Strange factory pattern

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jun 23 01:35:47 EDT 2010


En Tue, 22 Jun 2010 23:33:55 -0300, Zac Burns <zac256 at gmail.com> escribió:

> In the threading module there are several code bits following this
> convention:
>
> ###
> def Class(*args, **kwargs):
>     return _Class(*args, **kwargs)
>
> class _Class(...
> ###
>
> This is true for Event, RLock, and others.
>
> Why do this? It seems to violate the rule of least astonishment
> (isinstance(Event(), Event) raises an exception). I assume there must be
> some trade-off that the designer intended to achieve. So, what is that
> trade-off and when should I follow this in my code?

Those classes are not meant to be subclassed (I don't know *why*). From  
original module documentation (1998):

http://svn.python.org/view/python/trunk/Lib/threading_api.py?view=markup&pathrev=10430


"Lock()
     A factory function that returns a new primitive lock object...

RLock()
     A factory function that returns..."

Same for Condition, Semaphore, Event, but:

"Thread
     A class that represents a thread of control -- subclassable."

"Note that the classes marked as ''do not subclass'' are actually  
implemented as factory functions; classes are
shown here as a way to structure the documentation only."

And those classes have a big "*** DO NOT SUBCLASS THIS CLASS ***" message.  
The message never made into the documentation.


-- 
Gabriel Genellina




More information about the Python-list mailing list