forloop/EAFP中的异常处理

2024-04-19 00:16:21 发布

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

我有一个包含JSON数据的请求,它可能包含也可能不包含'items'键,如果包含,它必须是一个对象列表,我要单独处理。所以我必须写下这样的东西:

json_data = request.get_json()
for item in json_data['items']:
    process_item(item)

但是,由于'items'键的存在不是强制性的,因此需要采取额外的措施。我想遵循EAFP方法,因此将其包装成try ... except语句:

json_data = request.get_json()
try:
    for item in json_data['items']:
        process_item(item)
except KeyError as e:
    pass

让我们假设KeyError异常可能发生在process_item(...)函数中,这可能表示代码错误,因此它不应该被忽略,因此我想确保只捕获来自for语句谓词的异常,作为一种解决方法:

json_data = request.get_json()
try:
    for item in json_data['items']:
        process_item(item)
except KeyError as e:
    if e.message != 'items':
        raise e
    pass

但是

  1. 它看起来很难看
  2. 它依赖于process_item(...)实现的知识,假设KeyError('items')不能在它内部提升。你知道吗
  3. 如果for语句变得更复杂,例如for json_data['raw']['items']except子句也会变得更难阅读和维护。你知道吗

更新: 建议的替代方案

json_data = request.get_json()
try:
    items = json_data["items"]
except KeyError:
    items = []

for item in items:
    process_item(item)

本质上与

json_data = request.get_json()
if json_data.has('items')
    items = json_data['items']
else:
    items = []

for item in items:
    process_item(item)

所以我们在循环之前先检查一下。我想知道是否还有其他pythonic/EAFP方法?你知道吗


Tags: 方法injsonfordatagetrequestitems
2条回答

只有在访问"items"时才能捕获异常:

json_data = request.get_json()
try:
    items = json_data["items"]
except KeyError:
    items = []
for item in items:
    process_item(item)

但是,我们可以用对^{}函数的调用来替换try块,使其更简洁:

for item in request.get_json().get("items", []):
    process_item(item)

我认为最干净的选择是仅在试图检索与'items'键相关的数据的代码周围使用try块:

json_data = request.get_json()
try:
    items = json_data['items']
except KeyError:
    print "no 'items' to process"  # or whatever you want to...
else:
    for item in items:
        process_item(item)

这个布局将允许您在您认为合适的时候清楚地分离错误处理。如果需要,可以在for循环周围添加独立的try/except。你知道吗

相关问题 更多 >