Dynamic method parameter access?

Peter Otten __peter__ at web.de
Thu Feb 14 14:34:39 EST 2008


Dennis Kempin wrote:

> Chris schrieb:
>> On Feb 12, 9:38 pm, Dennis Kempin <den... at xardias.net> wrote:
>>> Hello,
>>>
>>> I have a set of some objects. With these objects I want to call a Python
>>> method. But the writer of the method shall have the option to select
>>> from these objects as method parameter.
>>>
>>> At the moment i use the following way to call a method with the a or b
>>> or both parameter.
>>>
>>> try:
>>>      method(a=value)
>>> except TypeError:
>>>      try:
>>>          method(b=value)
>>>      except TypeError:
>>>         method(a=value, b=value)
>>>
>>> This is getting really complex the more optional parameters I want to
>>> provide.
>>> Is there any other way to access the method parameter?
>>>
>>> Thanks in advance,
>>> Dennis
>> 
>> Instead of having set variable names, why not pass a dictionary ?
> 
> well of course it is possible that way. but it is not that.. "nice".
> I have a really a big bunch of functions that can access about 10
> parameters.
> at the moment i am using this alternative:
> 
> def method(paramA, paramB, paramC, **unused):
> 
> and the method is called via method(**params)
> 
>> def method(**kwargs):
>>     print kwargs
>> 
>> method(a='test1')
>> {'a': 'test1'}
>> 
>> method(a='test1', b='test2')
>> {'a': 'test1', 'b': 'test2'}
>> 
>> You can unpack the args once you are in your method to determine what
>> you need to do.
> that is the problem.. the most methods have only about 2-3 lines, it
> would get annoying when you always have to unpack the values..
> 
> thanks,
> Dennis

Maybe you like

import inspect

def format(kw):
    return ", ".join("%s=%r" % (key, kw[key]) for key in sorted(kw))

def dispatch(**kw):
    try:
        f = _funcs[tuple(sorted(kw))]
    except KeyError:
        raise TypeError("Don't know what to do with %s" % format(kw))
    else:
        return f(**kw)

_funcs = {}
def register(f):
    args = tuple(sorted(inspect.getargspec(f)[0]))
    if args in _funcs:
        raise ValueError
    _funcs[args] = f
    return f

@register
def add(a, b):
    return a + b

@register
def inv(a):
    return -a

@register
def square(b):
    return b*b

if __name__ == "__main__":
    print "1+2 =", dispatch(a=1, b=2)
    print "-3 =", dispatch(a=3)
    print "4*4 =", dispatch(b=4)
    print "oops", dispatch(c=5)

dispatch() uses argument names to choose a function it invokes.

Peter




More information about the Python-list mailing list