简体   繁体   English

Python嵌套的Try / Except / Else控制流

[英]Python Nested Try/Except/Else for Control Flow

What I'd like to achieve in the most elegant Python way: Try to find an object in the database on a certain filter. 我想以最优雅的Python方式实现的目标:尝试在特定过滤器上的数据库中查找对象。 Only if there is no result, then try to find the object using another filter. 仅当没有结果时,才尝试使用另一个过滤器查找对象。 If that returns no result, then the object does not exist, so insert a new instance. 如果没有返回结果,则该对象不存在,因此请插入一个新实例。

What I'm thinking: 我在想什么:

try:
    obj = session.query(model).filter_by(field_a).one()
except NoObjFound:
    try:
        obj = session.query(model).filter_by(field_b).one()
    except NoObjFound:
        insert_into_db(brand_new_obj)
else:
    update_the_obj(obj)

I'm not sure if this block is correct or the best way to handle what I'm trying to accomplish. 我不确定此块是否正确,还是处理我要完成的工作的最佳方法。

I would suggest something like: 我建议类似的东西:

for filter in (field_a, field_b):
    try:
        obj = session.query(model).filter_by(filter).one()
    except NoObjFound:
        pass # or 'continue'
    else:
        update_the_obj(obj)
        break
else:
    insert_into_db(brand_new_obj)

This will ensure that the correct things happen in the correct order, is more readable than nested try blocks and can easily be extended to add more filter s. 这将确保正确的事情以正确的顺序发生,比嵌套的try块更具可读性,并且可以轻松地扩展以添加更多的filter

This is incorrect. 这是不正确的。 Assuming you want to update_the_obj(obj) after finding the object independent of which filter found it, the else clause at the end is hidden to the inner filter. 假定您要查找与找到哪个过滤器无关的对象之后要update_the_obj(obj) ,则最后的else子句对内部过滤器隐藏。

You can try: 你可以试试:

obj = None
try:
    obj = session.query(model).filter_by(field_a).one()
except NoObjFound:
    try:
        obj = session.query(model).filter_by(field_b).one()
    except NoObjFound:
        insert_into_db(brand_new_obj)

if obj is not None:
    update_the_obj(obj)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM