Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass a keyword argument to a function when the name contains a dot `.`?

Given a function that accepts "**kwargs", e.g.,

def f(**kwargs):
     print(kwargs)

how can I pass a key-value pair if the key contains a dot/period (.)?

The straightforward way results in a syntax error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In [46]: f(a.b=1)
  Cell In[46], line 1
    f(a.b=1)
      ^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

>Solution :

Python functions only accepts valid python names (letters, underscore, and digits except for the first character), a dot is not allowed.

If you want to have a string a.b as parameter, then you must use a dictionary

f(**{'a.b': 1})
# {'a.b': 1}

You can combine this with other parameters:

f(x=2, **{'a.b': 1})
# {'x': 2, 'a.b': 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading