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

后端 未结 3 1509
长情又很酷
长情又很酷 2020-12-20 21:01
def func(**kwargs):
   for key, value in kwargs.items():
      # Is key always going to be a string?
      # Could it have spaces?
      pass

Two qu

3条回答
  •  醉梦人生
    2020-12-20 21:24

    Others have already covered the practical side of this, but I wondered if the documentation actually made any guarantees about keyword dictionaries' types.

    The documentation on call semantics does not specifically say keyword arguments will have type str in the dictionary.

    This is all that the documentation says about the type of the value of keyword arguments passed to a parameter declared with **:

    a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary

    So, theoretically, it appears that the documentation allows you to recieve keyword arguments as bytes, but this does not occur in any current implementation of Python 3.

    (For Python 2, the same holds, but for unicode instead of bytes.)

提交回复
热议问题