Callable modules?

Peter Hansen peter at engcorp.com
Mon Jul 22 20:16:24 EDT 2002


Chris Liechti wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote in
> news:3D3C971E.D0386D7D at engcorp.com:
> 
> > Paul Rubin wrote:
> >> 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).
> 
> no, no, read again... he already talks of instances, not classes. i.e. the
> __call__ method.

Oops, thanks for the correction.

In that case I'll change my comment to point out that for certain
classes, it is quite appropriate for their instances to have __call__
because they are intended to simulate methods or classes themselves
(i.e. other things which are normally callable).  They don't have 
__call__ just to let somebody use an unusual syntax to do something
that looks a little wordy done differently.

For example, given an object which has a method that does something
useful obj.doUsefulStuff() but which does not itself have any particular
reason to pretend to be a callable object, overriding __call__ to
let you do obj() and accomplish the same thing would just make the
code less readable, wouldn't it?

> > 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.
> 
> no need for such a restriction. just because an object has a __call__
> method does not mean that it must not have any others. a module is an
> object after all, so there is realy no good reason to prevent it from
> having a __call__ method...

Oh, I wouldn't want to _prevent_ it, but I can't see the extreme
need for it since the potential useful cases are so rare, IMHO.

> 
> > 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.
> 
> yeah, its not realy needed. however having a __call__ function in modules
> would be nice for plugin systems, where a plugin == a module/file.py. it
> would allow to init the plugin by calling the module instead of defining an
> init() function or whatsoever.

At first I thought this might be a nice idea, but then I realized on would
be doing it only to avoid typing "modulename.init()" which is so clear
and simple that I can't see why one would want to obfuscate matters by
doing modulename() instead.  

Maybe it's just me...

-Peter



More information about the Python-list mailing list