Python 函数的 kwargs 参数的键是否保证是字符串类型? [英] 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
关于 Python 中 kwargs 的两个问题.
Two questions about kwargs in Python.
- kwargs 的每个键都保证是 str 类型吗?如果是这样,我可以避免类型检查.
- 如果 #1 为真,是否可以保证每个键都没有空格?
推荐答案
直接传递的关键字参数必须是有效的 Python 标识符,是的,它将始终被视为字符串.其他任何东西都是 SyntaxError
.
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'}
关键字参数必须是字符串.其他任何东西都是 TypeError
.
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
这篇关于Python 函数的 kwargs 参数的键是否保证是字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!