Daniel Dow
Daniel Dow

Reputation: 517

Parsing **kwargs

I'm looking for a more elegant way of parsing kwargs. I'm still wet under the ears with Python and this will be my first use of kwargs in a def. So here's the scenario:

def function(arg, arg, **kwargs)
    other_function(arg, arg, **kwargs)

def other_functions(arg, arg, **kwargs)
    if kwargs:
         name = etree.SubElement(params,'thing','value from kwargs')
         return name
    name = etree.SubElement(params,'thing')
    return name

I feel like there's a better way to handle this than by using an if to se if there are **kwargs. Is this the right way to do that?

Thanks for any help!

Dan

Upvotes: 2

Views: 2515

Answers (1)

OozeMeister
OozeMeister

Reputation: 4859

What you have will work, but you could do this:

def other_function(parent, *args, **kwargs):
    return etree.SubElement(parent, 'thing', attrib=kwargs)

The *args becomes the variable args which is literally just a tuple of values. Likewise, **kwargs becomes the variable kwargs which is literally just a dict.

SubElement has an optional attrib parameter which allows you to pass in a dictionary of values to add to the element as XML attributes. So, you can literally pass in kwargs as a value.

So, calling other_function like so will produce the following output:

>>> print etree.tostring(other_function(parent, my_attrib='my value'))
'<thing my_attrib="my value" />'

And calling other_function without any key word arguments passed in will produce the following output:

>>> print etree.tostring(other_function(parent))
'<thing />'

as kwargs will be an empty dict if no keyword arguments are used.

Note 1: since **kwargs allows you to pass anything in, this allows for creating anything as an attribute on the SubElement which may not be the desired intent if any of the values in kwargs are to be used elsewhere, e.g. flags for the function.

Note 2: the variable names args and kwargs are just convention. You can use **atrib and pass attrib=attrib to SubElement and it will work just the same.

Upvotes: 2

Related Questions