Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python keyword arguments with hyphen

I have a keyword argument function:

def f1(**kw):
    for key,val in kw.iteritems():
        print "key=%s val=%s" % (key,val)

f1(Attr1 = "Val1", Attr2 = "Val2")  # works fine.

f1(Attr1-SubAttr = "Val1", Attr2 = "Val2")  # complains about keyword being an expression.

f1("Attr1-SubAttr" = "Val1", Attr2 = "Val2")  # doesn't work either.

How do I pass in keywords with a hyphen? I don't have control over these keywords since I am parsing these from an existing legacy database.

Thanks! -kumar

like image 756
Kumar Avatar asked Jun 09 '14 13:06

Kumar


People also ask

What is a hyphen in Python?

Hyphens Are Word Boundaries on the Web git repository names. Python packages, specifically those in PyPI (the main repository for pip )

What are arbitrary keyword arguments in python?

Arbitrary Keyword Arguments, **kwargsIf you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.

How would you define a function with arbitrary keyword arguments?

If you need to write a function that accepts arbitrary keyword arguments, you can use the ** operator in your function definition.


1 Answers

Keyword arguments must be valid Python identifiers; these don't allow for - as that's reserved for subtraction.

You can pass in arbitrary strings using the **kwargs variable keyword argument syntax instead:

f1(**{"Attr1-SubAttr": "Val1", "Attr2": "Val2"})
like image 76
Martijn Pieters Avatar answered Sep 19 '22 15:09

Martijn Pieters