2

I have the following function:

def foo(a, b, c):
    print "Hello"

Let's say I know it exists, and I know it takes three parameters named a, b and c, but I don't know in which order.

I want to be able to call foo given a dictionary like:

args = { "a": 1, "b" : 17, "c": 23 }

Is there a way to find out in which order the parameters are to be passed?

1 Answer 1

9

You don't need to; let Python figure that out for you:

foo(**args)

This applies your dictionary as keyword arguments, which is perfectly legal. You can use the arguments to foo() in any order when you use keyword arguments:

>>> def foo(a, b, c):
...     print a, b, c
... 
>>> foo(c=3, a=5, b=42)
5 42 3
>>> args = {'a': 1, 'b' : 17, 'c': 23}
>>> foo(**args)
1 17 23

You can still figure out the exact order, using the inspect.getargspec() function:

>>> import inspect
>>> inspect.getargspec(foo)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)

But why have a dog and bark yourself?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.