__call__ bad style? (was Re: Callable modules?)
Jonathan Hogg
jonathan at onegoodidea.com
Thu Jul 25 03:57:03 EDT 2002
On 24/7/2002 17:11, in article BkA%8.112577$Jj7.2658921 at news1.tin.it, "Alex
Martelli" <aleax at aleax.it> wrote:
> You have a point. Such a need is so rare and weird that I would not be
> highly troubled by having to use weird ways to meet it. However, taking
> "callability" as outside the range of polymorphically emulable behaviors
> would indeed reduce regularity, so it might be a bad idea even though the
> serious use cases for it ARE weird:-).
You seem to be starting from the point of view that __call__ is bad and
using that as an argument that serious uses of __call__ must therefore be
rare and weird ;-)
I would use an object with __call__ for even trivial callable objects
because of the ability to redefine the 'repr' interface and access
attributes.
Another thread here discussed wrapping a function to provide 'before' and
'after' hooks. This is exactly the situation where I would use a __call__
interface. Consider:
>>> def hello( name ):
... print 'Hello', name
...
>>> def upper( args, keys ):
... return (args[0].upper(),), keys
...
>>> hello = wrap( hello, before=upper )
>>> hello( 'Jonathan' )
Hello JONATHAN
>>> hello
<wrapped function hello at 0x40f3e8>
>>> hello.before
<function upper at 0x40fe68>
>>>
Here 'wrap' is a class that implements the __call__ interface. The resulting
object behaves just like the original function so I can drop it into
existing code, it explains what it is via __repr__, and provides access to
the state for examination. Try something similar with a closure or a bound
method.
-__call__-doesn't-kill-readability-people-kill-readability-;)-ly y'rs,
Jonathan
More information about the Python-list
mailing list