简体   繁体   English

如果我的字典缺少必需的键,我应该提出哪种异常类型?

[英]What exception type should I raise if my dictionary is missing required keys?

I am testing that data (dictionary), used in Django's render(request, url, data) , has some required keys. 我正在测试在Django的 render(request, url, data)使用的data (字典)具有一些必需的键。 I will raise an exception if the required keys are missing. 如果缺少必需的键,我将引发一个异常。 What exception type is best suited for this? 哪种异常类型最适合此?

Is there a better way to think about this? 有没有更好的方式考虑这一点?

For consistency with regular dicts, I would think a KeyError would be appropriate 为了与常规命令保持一致,我认为KeyError是合适的

>>> d = {'foo': 'bar'}
>>> d[5]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    d[5]
KeyError: 5

KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys. 在现有键集中找不到映射(字典)键时引发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当请求非法状态时我应该提出什么Python异常? - What Python Exception should I raise when illegal state is asked for? 当转储到yaml时,我应该添加些什么以在某些键下生成新行? - What should I add to my python dictionary to generate a new line beneath certain keys when dumped to yaml? 当在数据库中找不到对象时,SQLAlchemy模型应引发哪种类型的异常? - What type of Exception should SQLAlchemy model raise when an object is not found in DB? 我应该为只能调用一次的函数引发python中的哪种标准异常 - What kind of the standard exception in python should I raise for a function which can only be invoked once 在我的情况下,我应该使用字典还是列表? - What should I use dictionary or list in my case? 发生异常时,我应该提出还是冒犯? - When exception occurs should I raise or bubble it up? 对于 Python 中的错误/非法参数组合,我应该引发哪个异常? - Which exception should I raise on bad/illegal argument combinations in Python? 我应该针对REST API错误提出哪个异常? - Which exception should I raise for a REST API error? 引发与意外文件类型相关的异常的最Pythonic方法是什么? - What is the most Pythonic way to raise an exception related to an unexpected file type? 使用丢失的文件名引发异常 - raise an exception with the name of the file that is missing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM