python - "continue"是逃离 try catch block 的 Pythonic 方式吗?

标签 python django

我是 django 的新手,想通过简单的 django 应用程序来了解更多信息,在代码中的一个地方我不得不选择 locationName并获取与 locationName 匹配相同 ID 的元素在一张 table 上。当我开始想是continue逃避 for 循环的最 pythonic 方式?

有问题的代码如下:

for locationName in locationGroup:
    idRef = locationName.id
    try:
        element = location.objects.order_by('-id').filter(name__id=idRef)[0]
    except IndexError:
        continue

最佳答案

如果在 except 子句之后有一些您不想执行的代码,continue 是完全有效的,否则有些人可能会觉得 pass 更合适。

for x in range(y):
    try:
        do_something()
    except SomeException:
        continue
    # The following line will not get executed for the current x value if a SomeException is raised
    do_another_thing() 

for x in range(y):
    try:
        do_something()
    except SomeException:
        pass
    # The following line will get executed regardless of whether SomeException is thrown or not
    do_another_thing() 

关于python - "continue"是逃离 try catch block 的 Pythonic 方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11467985/

相关文章:

python - 使用 Bottle 或 Flask 将多个页面路由到同一个模板,并带有参数

Python:创建目录中以 ".json"结尾的所有文件的 zip 文件

python - 在我的 celery 应用程序中使用 django ORM 出现错误

django - 在单独的线程中同步运行异步代码

python - Django Channels/Daphne 中的 Websocket 超时

python - Gnupg 不输出加密文件

python - 如何确保Python中只有一个线程实例在运行?

python - Django 最佳实践。形式

Django - 无效的 block 标记 : 'csrf_tokan' , 预期 'endblock'

javascript - 如何在导入语句中使用变量