Search code examples
pythonpython-3.xkeyword-argument

Are the keys of a kwargs argument to Python function guaranteed to be type string?


def func(**kwargs):
   for key, value in kwargs.items():
      # Is key always going to be a string?
      # Could it have spaces?
      pass

Two questions about kwargs in Python.

  1. Is every key of kwargs guaranteed to be of type str? If so, I can avoid type checking.
  2. If #1 is true, would every key be guaranteed to not have spaces?

Solution

  • A keyword argument passed directly must be a valid Python identifier, and yes it will always be treated as strings. Anything else is a SyntaxError.

    f(foo=1) # Works
    f($=1) # Fails
    f(1=1) # Fails
    

    Although, you can also give keyword arguments through unpacking. In this case, your keyword arguments must be strings still, but they can take any format.

    Let's define a dummy function to test this.

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

    A keyword argument can contain a space or be a string of digits. It can even contain special characters.

    f(**{"hello world": 'foo'}) # prints {'hello world': 'foo'}
    f(**{"1": 'foo'}) # prints {'1': 'foo'}
    f(**{"$": 'foo'}) # prints {'$': 'foo'}
    

    A keyword argument must be a string. Anything else is a TypeError.

    f(**{1: 'foo'}) # TypeError: f() keywords must be strings
    f(**{b'foo': 1}) # TypeError: f() keywords must be strings