Dynamic method parameter access?

Chris cwitts at gmail.com
Tue Feb 12 15:12:53 EST 2008


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 ?

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.



More information about the Python-list mailing list