A __call__ "method" which is itself another callable class instance?

Chris Angelico rosuav at gmail.com
Fri May 8 08:50:22 EDT 2015


On Fri, May 8, 2015 at 10:24 PM, Skip Montanaro
<skip.montanaro at gmail.com> wrote:
> The question for the esteemed gathering here: have you ever encountered the
> need for this class-instance-as-a-dunder-call-method before? Perhaps in some
> sort of code generation situation? Or cleaner functions-with-attributes?

I've never actually done it, but there've been times when I've
considered setting __call__ to be a class, rather than an actual
function. (Though the time I wanted it, I was wanting to set __call__
on a module, and I ended up not bothering with the hassle that that
entails.) Python classes are automatically factories of themselves
[1], so there should be no difference between calling a class and
calling a function that passes through to the class:

foo = Bar
@functools.wraps(Bar)
def foo(*args, **kw): return Bar(*args, **kw)

In fact, I would fully expect things like functools.wraps to work just
fine on classes, types, and instances of classes with __call__
methods, just as they would with functions - in the same way that
you'd expect a def function to work just as well as a lambda function.

If your code _does_ get into an infinite loop, so would calling the
function. I wouldn't see a problem with that being rewritten as "while
True", just to ensure the equivalencies.

ChrisA

[1] https://xkcd.com/387/



More information about the Python-list mailing list