我有一个以字典作为参数的函数。我将向它传递各种词典,这些词典的条目比函数内部使用的条目多。此外,我想在函数定义中查看需要哪些键。所以我写
def fun(indict=dict(apple=None, pear=None)):
但是,该函数现在接受任何输入作为 indict
。有没有一种聪明的写作方式
any dictionary that has at least the keys 'apple' and 'pear' is accepted.
有点像
def fun(indict=dict(apple=NeedsToBeSpecified, pear=NeedsToBeSpecified)):
最佳答案
在python3.x中,可以使用function annotations :
>>> def foo(indict: dict(apple=None, pear=None)):
... print(indict)
...
>>> foo(dict())
{}
你甚至可以疯狂地使用现在更广泛接受的(由解释器)Ellipsis
literal
>>> def foo(indict: dict(apple=None, pear=None, extra_items=...)) -> int:
... if any(x not in indict for x in ('apple', 'pear')):
... raise ValueError('message here...')
... print(indict)
... return 3
...
>>> foo({})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
ValueError: message here...
>>> foo({'apple':6, 'pear':4})
{'pear': 4, 'apple': 6}
3
>>> foo({'apple':6, 'pear':4, 'carrot':30000})
{'carrot': 30000, 'pear': 4, 'apple': 6}
3
正如您从我的第一个示例中看到的那样,注解 it 不会强制任何内容。你必须在函数本身中执行验证,尽管我想你可以从注释1 中反省所需的键,如果你想让它保持干燥,但它可能不值得仅仅为了 2键...
在 python2.x(和更传统的)中,也许您只想将信息放在文档字符串中;-)——我建议您也为 python3.x 这样做,因为这是传统的地方去寻找文档......
1keys = foo.__annotations__['indict'].keys() - {'extra_items'}
更新
请注意,现在有了像 mypy 这样的花哨的东西,这个答案可能有点过时了。您可能会考虑使用 TypedDict
进行注释来自 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:
...
关于python - 带有一些强制键作为功能输入的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21014761/