英文:
How can I get a dictionary of kwargs, while only allowing certain keywords?
问题
我正在编写一个函数,需要接受多个关键字参数(kwargs),它们都默认为None
,然后将它们存储在一个字典中。如果调用时使用了不支持的参数,它需要引发普通的TypeError
异常。有没有比这更好的方法?
def my_function(a=None, b=None, c=None, d=None, e=None):
dictionary = {"a": a, "b": b, "c": c, "d": d, "e": e}
# ...
英文:
I am writing a function that needs to take several kwargs, all defaulting to None
, and store them in a dictionary. It needs to give the normal TypeError
if called with an unsupported argument. Is there a better way than this?
def my_function(a=None, b=None, c=None, d=None, e=None):
dictionary = {"a": a, "b": b, "c": c, "d": d, "e": e}
# ...
</details>
# 答案1
**得分**: 1
根据您的要求,以下是内容的中文翻译:
根据我的观点,您当前的方法是直观且最佳的,但如果您想使它更加简单,您可以尝试使用 [inspect](https://docs.python.org/3/library/inspect.html) 模块。
```python
import inspect
def my_function(a=None, b=None, c=None, d=None, e=None):
dictionary = inspect.getargvalues(inspect.currentframe()).locals
print(dictionary) # {'a': 'x', 'b': None, 'c': 1, 'd': None, 'e': [1, 2, 3]}
my_function(a="x", e=[1, 2, 3], c=1)
英文:
In my opinion, your current approach is intuitive and best, but if you want to make it even easier, you can try inspect module.
import inspect
def my_function(a=None, b=None, c=None, d=None, e=None):
dictionary = inspect.getargvalues(inspect.currentframe()).locals
print(dictionary) # {'a': 'x', 'b': None, 'c': 1, 'd': None, 'e': [1, 2, 3]}
my_function(a="x", e=[1, 2, 3], c=1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论