What are peoples’ opinions on using the __call__. I’ve only very rarely seen it used, but I think it’s a very handy tool to use when you know that a class is going to be used for some default behaviour.
What are peoples’ opinions on using the __call__ . I’ve only very rarely seen
Share
I think your intuition is about right.
Historically, callable objects (or what I’ve sometimes heard called “functors”) have been used in the OO world to simulate closures. In C++ they’re frequently indispensable.
However,
__call__has quite a bit of competition in the Python world:I’d say the time to use
__call__is when you’re not better served by one of the options above. Check the following criteria, perhaps:run()ordoStuff()orgo()or the ever-popular and ever-redundantdoRun(), you may have a candidate.One example I like is UI command objects. Designed so that their primary task is to execute the comnand, but with extra methods to control their display as a menu item, for example, this seems to me to be the sort of thing you’d still want a callable object for.