Search code examples
pythonkeyword-argument

Accepting integers as keys of **kwargs


Keywords have to be strings

>>> def foo(**kwargs):
...     pass
... 
>>> foo(**{0:0})
TypeError: foo() keywords must be strings

But by some black magic, namespaces are able to bypass that

>>> from types import SimpleNamespace
>>> SimpleNamespace(**{0:0})
namespace()

Why? And how? Could you implement a Python function that can receive integers in the kwargs mapping?


Solution

  • SimpleNamespace now rejects integer keyword keys. As Martijn supposed, the original behavior was a bug. It seems that it was fixed by bpo-31655: Validate keyword names in SimpleNamespace constructor in v3.9.0b2, and then backported to 3.6.