具有一些强制键作为函数inpu的字典

2024-10-01 19:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它有一个字典作为参数。我将把各种字典传递给它,这些字典的词条比函数中使用的几个词条还要多。另外,我想看看函数定义中需要什么键。所以我写了

def fun(indict=dict(apple=None, pear=None)):

但是,该函数现在接受任何输入作为indict。有没有聪明的写作方法

^{pr2}$

有点像

def fun(indict=dict(apple=NeedsToBeSpecified, pear=NeedsToBeSpecified)):

Tags: 函数noneapple参数字典定义defdict
3条回答

你可以检查一下:

def fun(indict=dict(apple=None, pear=None)):
    if "apple" not in indict and "pear" not in indict:
        raise ValueError("'indict' must contain...")

但是,在Python中,您不应该真正使用dictionary(或其他可变的)默认参数;相反,请选择:

^{pr2}$

或者您可以使用update来确保这两个键始终存在,而不是强制调用者提供它们:

def fun(indict=None):
    defdict = {"apple": None, "pear": None}
    if indict is  not None:
        defdict.update(indict)
    indict = defdict

在python3.x中,可以使用function annotations

>>> def foo(indict: dict(apple=None, pear=None)):
...     print(indict)
... 
>>> foo(dict())
{}

您甚至可以疯狂地使用现在更为广泛接受的(由解释器)Ellipsis文本

^{pr2}$

正如您从我的第一个示例中看到的那样,它的注释并没有实施任何东西。您必须在函数本身中执行验证,尽管我认为如果您想保持干燥,您可以从注释1中反省所需的键,但仅为2个键所做的努力可能不值得。。。在

在python2.x(以及更传统的)中,也许您只想将信息放入docstring;—)——我建议您对python3.x也这样做,因为这是查找文档的传统位置。。。在

1keys = foo.__annotations__['indict'].keys() - {'extra_items'}

更新 请注意,现在有了像mypy这样的花哨事物,这个答案可能有点过时了。您可以考虑使用^{}mypy_extensions进行注释。这应该为用户设置期望值,如果使用mypy之类的类型检查器,甚至可能有助于捕获一些错误。在

from mypy_extensions import TypedDict

class Apple:
    """Represent an Apple."""

class Pear:
    """Represent a Pear."""

# "annotation-type" for a dictionary that has an apple and pear key whose values are Apple and Pear instances.
FruitBowl = TypedDict("FruitBowl": {"apple": Apple, "Pear": Pear})

def foo(indict: FruitBowl) -> int:
    ...

我看到了很多复杂的答案,对于一些非常琐碎的事情:

def yourfunc(apple, pear, **kw):
   your_code_here

然后在调用时使用**kw语法传递indict,即:

^{pr2}$

不需要检查任何内容,Python将自己执行并引发适当的异常。在

如果无法更改调用语法,只需使用以下简单的修饰符将yourfunc包装起来:

def kw2dict(func):
    def wrap(**kw):
        return func(kw)
    return wrap

(注意:应使用functools正确包装装饰器)

相关问题 更多 >

    热门问题