code explanation

Steven D'Aprano steve+comp.lang.python at
Tue Jan 15 05:38:09 CET 2013

On Mon, 14 Jan 2013 23:00:16 -0500, Rodrick Brown wrote:

> Can someone explain what's going on here.
> def _build_magic_dispatcher(method):
>     def inner(self, *args, **kwargs):
>         return self.__dict__[method](*args, **kwargs)
>     inner.__name__ = method
>     return inner
> Thanks.

This is a factory function, probably intended to be used as a decorator:

class K:
    def something(self, x, y, z): ...

except that it appears to be broken. It seems to be expecting a *string*, 
the name of a method, despite the function parameter claiming to require 
a method itself. So maybe you use it like this:

class K:
    def __init__(self):
        self.parrot = _build_magic_dispatcher("parrot")

or something similar. Without seeing the context, it's hard for me to 
tell whether it works or is broken. I suspect it is broken, or useless, 
or both.

So, this factory function seems to take the *name* of a method as 
argument. Then it builds an inner method, which accepts arbitrary 
arguments (args and kwargs), renames the inner method to the name you 
passed as argument, and returns it.

The inner method simply looks up an attribute with the same name, and 
calls it as a function with whatever args and kwargs it gets.

Does this help?


More information about the Python-list mailing list