Callable or not callable, that is the question!
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Jul 12 05:49:14 EDT 2013
On Fri, 12 Jul 2013 07:36:30 +0000, Duncan Booth wrote:
> To be a convincing use-case you would have to show a situation where
> something had to be both a static method and a utility method rather
> than just one or the other and also where you couldn't just have both.
I have a class where I have a function that needs to be called both while
the class is being constructed, and afterwards:
class Example:
@staticmethod
def do_stuff(arg):
...
do_stuff(23) # This doesn't work.
Example.do_stuff(42)
I have work-arounds: inside the class, I call do_stuff.__func__ instead
of do_stuff, but really, that's ugly and distracting and merely a work-
around for the fact that staticmethods aren't callable. To make them
callable is trivially easy: they just need a __call__ method that calls
__func__ for you.
> If you can persuade me that you need _handle_bool as both a static
> method and a utility function, you probably also need to explain why you
> can't just use both:
>
> class Parser:
> def _handle_bool(input): ...
> handle_bool = staticmethod(_handle_bool)
That's extremely inelegant. Why have two functions for something which is
conceptually one?
--
Steven
More information about the Python-list
mailing list