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中,您不应该真正使用dictionary(或其他可变的)默认参数;相反,请选择:
^{pr2}$或者您可以使用
update
来确保这两个键始终存在,而不是强制调用者提供它们:在python3.x中,可以使用function annotations:
您甚至可以疯狂地使用现在更为广泛接受的(由解释器)
^{pr2}$Ellipsis
文本正如您从我的第一个示例中看到的那样,它的注释并没有实施任何东西。您必须在函数本身中执行验证,尽管我认为如果您想保持干燥,您可以从注释1中反省所需的键,但仅为2个键所做的努力可能不值得。。。在
在python2.x(以及更传统的)中,也许您只想将信息放入docstring;—)——我建议您对python3.x也这样做,因为这是查找文档的传统位置。。。在
1
keys = foo.__annotations__['indict'].keys() - {'extra_items'}
更新 请注意,现在有了像mypy这样的花哨事物,这个答案可能有点过时了。您可以考虑使用^{} 从
mypy_extensions
进行注释。这应该为用户设置期望值,如果使用mypy
之类的类型检查器,甚至可能有助于捕获一些错误。在我看到了很多复杂的答案,对于一些非常琐碎的事情:
然后在调用时使用
^{pr2}$**kw
语法传递indict
,即:不需要检查任何内容,Python将自己执行并引发适当的异常。在
如果无法更改调用语法,只需使用以下简单的修饰符将
yourfunc
包装起来:(注意:应使用functools正确包装装饰器)
相关问题 更多 >
编程相关推荐