Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #90162

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

References <CANc-5UycxL5GUxBnk1CsjZOekpc0WG1575WX8HdKAHFwBEimdA@mail.gmail.com>
Date 2015-05-08 22:50 +1000
Subject Re: A __call__ "method" which is itself another callable class instance?
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.245.1431089425.12865.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, May 8, 2015 at 10:24 PM, Skip Montanaro
<skip.montanaro@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/

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: A __call__ "method" which is itself another callable class instance? Chris Angelico <rosuav@gmail.com> - 2015-05-08 22:50 +1000

csiph-web