Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add keyword arguments

Tags:

python

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!

like image 741
tabchas Avatar asked Aug 05 '13 10:08

tabchas


1 Answers

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)
like image 187
Martijn Pieters Avatar answered Nov 08 '22 22:11

Martijn Pieters