5

If I have a function:

def add(**kwargs):
    for key, value in kwargs.iteritems():
        print "%s = %s" % (key, value)

How can I dynamically add keyworded arguments to this function? I am building an HTML Generator in Python, so I need to be able to add keyworded arguments depending on which attributes the user wants to enable.

For instance, if the user wants to use the name attribute in a form, they should be able to declare it in a list of stored keyword arguments (don't know how to do this either). This list of stored keyword arguments should also contain the value of the variable. For instance, if the user wants the attribute name to be "Hello", it should look like and be passed to the function as so:

name = "Hello" (example)

Let me know if you guys need more information. Thanks!

1

1 Answer 1

16

You already accept a dynamic list of keywords. Simply call the function with those keywords:

add(name="Hello")

You can use the **expression call syntax to pass in a dictionary to a function instead, it'll be expanded into keyword arguments (which your **kwargs function parameter will capture again):

attributes = {'name': 'Hello'}
add(**attributes)
1
  • That's exactly what I need. Didn't know I could add in a dictionary like that. Thanks!
    – tabchas
    Aug 5, 2013 at 10:40

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.