How can I get a dictionary of kwargs, while only allowing certain keywords?

huangapple go评论54阅读模式
英文:

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)  # {&#39;a&#39;: &#39;x&#39;, &#39;b&#39;: None, &#39;c&#39;: 1, &#39;d&#39;: None, &#39;e&#39;: [1, 2, 3]}


my_function(a=&quot;x&quot;, 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)  # {&#39;a&#39;: &#39;x&#39;, &#39;b&#39;: None, &#39;c&#39;: 1, &#39;d&#39;: None, &#39;e&#39;: [1, 2, 3]}


my_function(a=&quot;x&quot;, e=[1, 2, 3], c=1)

huangapple
  • 本文由 发表于 2023年6月15日 01:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定