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!

tabchas
  • 1,374
  • 2
  • 18
  • 37
  • Possible duplicate of [Dynamic Keyword Arguments in Python?](https://stackoverflow.com/questions/337688/dynamic-keyword-arguments-in-python) – 0 _ Sep 28 '17 at 15:29

1 Answers1

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343