Summer reading list

John J. Lee jjl at pobox.com
Fri Aug 15 17:52:31 EDT 2003


mis6 at pitt.edu (Michele Simionato) writes:

> "Joe Cheng" <jmcheng at alum.mit.edu> wrote in message
>  news:<mailman.1060713261.4958.python-list at python.org>...
> > To me it sounds disturbingly like "Procedures are more flexible than
> > classes because you can compose classes out of procedures."
> 
> I would subscribe that. Not that I dislike inheritance, but  I don't kill
> a mosquito with a bazooka.
> 
> Let me give a real life example, happened to me recently. 
> 
> I had a class manipulating text, with a "dedent" method. It turns out
> that the "textwrap" module included in the Python 2.3 distribution
> contains a "dedent" function doing exactly the same.
> Then I had the satisfaction of killing my own implementation,
> and to add to my class the textwrap.dedent function just with one
> line of code, "dedent=staticmethod(textwrapper.dedent)". I am
> very happy with that because:

[...snip usual reasons for reusing code...]

> The fact that "dedent" was a function and not a method in a class
> made my life easier. I had not to worry about inheriting from another
> class with potential name clashes with my own, and "dedent" was the
> only function I needed.
> 
> Fortunately, quite a lot of modules in the standard library are
> written without a class interface and I would date say I have never 
> seen an example of usage of a class when the class is not needed.
> 
> In other words: most of the time a lightweight approach is more than
> appropriate, why should I be forced to take a heavy weight approach?
> The fact of having "free" functions (i.e. not bounded to classes) is
> to me a big strenght of Python and it helps reuse of code quite a lot.

All fine.


> To reuse classes is good, but typically only works when you know
> about the class you want to inherit *before* you start coding your
> own class; on the other hand, it is quite easy to add functions
> or methods to your class even *after* you wrote it.
[...]

But I don't think that makes any sense.  As I'm certain you know,
there would be nothing to stop you using a class in exactly the same
way you used the function, because reuse != inheritance.  Functions
can be implemented in terms of classes, and classes can be implemented
in terms of functions.

The only reason it's good that Python library uses functions sometimes
instead of classes is as you say: KISS.  If it only needs a function,
use a function.


John




More information about the Python-list mailing list