Class == factory function considered harmful? (Re: Thoughts about Python)

Greg Ewing (using news.cis.dfn.de) wmwd2zz02 at sneakemail.com
Tue Feb 24 22:37:24 EST 2004


Paul Prescod wrote:
> Changing from a class to a function is never really very safe:
> 
> class myobject(File):
>     ...
> 
> if isinstance(myobject, File):
>     ....
> 
> How can you change File to be just a function safely?

You can't, obviously. This demonstrates that there *is*
an important distinction to be made between classes and
functions -- you can subclass one and not the other!

Arguments like this (and others, such as the capability-based
security model problems) are making me re-consider whether
having classes also be factory functions is really such
a good idea. There are two distinct ways of using classes
in Python:

1. As a base class
2. As a factory function

and these have different degrees of coupling to the
implementation. Use (1) requires it to really be a
class, whereas (2) only requires it to be a callable
object.

For use (1), there is an advantage in having classes
named differently from functions -- if it's named like
a class, you know it's a class and can therefore
subclass it.

But for use (2), it's a disadvantage, since if something
starts out as a factory function and later changes into
a (published) class, all code using it has to change.

The only way I can see of reconciling these is to adopt
the convention that whenever you publish a class Foo,
you also publish a factory function foo() that instantiates
Foo. Users of it are expected to use Foo when subclassing
and foo() when instantiating.

Now, if you change the implementation so that Foo is
no longer a class, code which subclasses Foo will break --
there's no avoiding that. But code which only instantiates,
using foo(), will keep working.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list