Callable modules?

Peter Hansen peter at engcorp.com
Mon Jul 22 19:37:02 EDT 2002


Paul Rubin wrote:
> 
> Stefan Schwarzer <sschwarzer at sschwarzer.net> writes:
> > > Just to not have to say "foo.foo()" or "from foo import foo".
> > > If the main purpose of the module is to provide one function, I think
> > > it's cleaner to be able to import the module and call the function
> > > without special tricks.
> >
> > I consider it cleaner to be explicit, and import the module and call
> > its function. :-)
> 
> Does that reasoning not also apply to class instances?  Why should
> class instances be callable through the __call__ method?

Because that's how you create an instance of the class (i.e. an object).
If you have a reasonable parallel for all modules _in general_ then *that* 
would be the one reasonable case in which to use this scheme.  I can't 
think of a good one, myself.

> > How many actual cases do you know of where a module has a single function?
> > Aren't they rare?
> 
> I've written several, there are several in the Python library, and
> remember that it's not necessary for the module to have a single
> function for a __call__ interface to be useful.  __call__ makes sense
> if there's a most-important or most-frequently-used function in the
> module.  It's ok if there are other functions too.

Although you can do as you wish, of course, I want to chime in
with a "this is a really bad idea" and hope you don't follow through
on it.  This is, even in the best case, going to make your code 
less readable to anyone else.  It is also likely to cause maintainability
problems because making the claim "but this module has only one function!"
almost certainly means it will not stay that way forever.

Any time you find yourself going to a lot of effort to work around what
feels like a small wart or syntactical ugliness (neither of which
even apply in this case, IMHO) you should probably stop yourself and
say "whoa, what was I thinking?" and do it the standard way.

(All free advice of course, worth what it cost you. :-)

-Peter



More information about the Python-list mailing list