Directly calling python's function arguments dispatcher

Pascal Chambon chambon.pascal at wanadoo.fr
Sun Dec 12 16:15:43 EST 2010


Hello

I've encountered several times, when dealing with adaptation of function 
signatures, the need for explicitly resolving complex argument sets into 
a simple variable mapping. Explanations.


Consider that function:

def foo(a1, a2, *args, **kwargs):
     pass

calling foo(1, a2=2, a3=3)

will map these arguments to local variables like these:
{
'a1': 1,
'a2': 2,
'args': tuple(),
'kwarg's: {'a3': 3}
}

That's a quite complex resolution mechanism, which must handle 
positional and keyword arguments, and deal with both collision and 
missing argument cases.

Normally, the simplest way to invoke this mechanism is to define a 
function with the proper signature, and then call it (like, here, foo()).

But there are cases where a more "meta" approach would suit me well.

For example when adapting xmlrpc methods : due to the limitations of 
xmlrpc (no keyword arguments), we use a trick, i.e our xmlrpc functions 
only accept a single argument, a "struct" (python dict) which gets 
unpacked on arrival, when calling the real functions exposed by the 
xmlrpc server.

But on client side, I'd like to offer a more native interface (allowing 
both positional and keyword arguments), without having to manually 
define an adapter function for each xmlrpc method.

To summarize, I'd like to implement a magic method like this one (please 
don't care about performance isues for now):

class XmlrpcAdapter:
     def __getattr__(self, funcname):
         # we create an on-the-fly adapter
         def adapter(*args, **kwargs):
             xmlrpc_kwargs = _resolve_func_signature(funcname, *args, 
**kwargs)
# we call the remote function with an unique dict argument
             self.xmlrpc_server.call(funcname, xmlrpc_kwargs)
                 return adapter

As you see, all I need is _resolve_func_signature(), which is actually 
the routine (internal to the python runtime) which transforms complex 
function calls in a simple mapping of variables to be added to the 
function local namespace. Of course this routine would need information 
about the target functions' signature, but I have that info available 
(for example, via a set of functions that are a mockup of the real 
xmlrpc API).

Is that routine exposed to python, somewhere ? Does anybody know a 
working implementation here or there ?

Thanks for the help,
regards,
Pakal






More information about the Python-list mailing list