0

I have a Python function that takes one required parameter and four optional ones. If an optional param has no value it needs to be omitted from the call to the function. An example call will be like the following with all params specified.

MyFunction(required='Delta', param1='ABC', param2='XYZ', ID=1234, title='Imp Info') 

I would like to gather all of my optional params into a variable and then pass a variable into the function. This will make handling the optional params easier. Something like the following:

myVar = "param2='XYZ', ID=1234, title='Imp Info'"
MyFunction(param1='Delta', myVar) 

I've tried the above but it failed with a syntax error. How can I pass function params as a variable? I appreciate any guidance.

asked Jan 24, 2016 at 6:37
2
  • 2
    MyFunction(required, **kwargs), use a dict of kwargs... Commented Jan 24, 2016 at 6:38
  • Use **kwargs it's a dictionary and can be unpacked Commented Jan 24, 2016 at 6:40

2 Answers 2

2

Don't pass them in as a string; pass them in as an unpacked dictionary:

myVar = {'param2':'XYZ', 'ID':1234, 'title':'Imp Info'}
MyFunction(param1='Delta', **myVar)

The ** will unpack the dictionary and send each element as a named argument.

answered Jan 24, 2016 at 6:39
Sign up to request clarification or add additional context in comments.

Comments

1

You can use MyFunction(parameters, *args, **kwargs), or you can define a method instead that splits the string by space and either parses or uses eval (not recommended) to assign the variable.

answered Jan 24, 2016 at 6:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.