“continue”是Python中从try catch块中跳出的惯用方式吗?

4

我刚开始学习django,想做一个简单的django应用来更好地了解它。在代码的某个位置,我需要挑选locationName并获取与表中相同id匹配的元素。当我开始思考如何使用最pythonic的方式来跳出for循环时,我不禁想起了continue

下面是相关代码:

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

11
使用关键字的本意来编写代码,是最符合 Pythonic 风格的做法。 - Martijn Pieters
1
дҪ жғіиҰҒд»Һ try/catch еқ— (pass) дёӯвҖңи·іеҮәвҖқеҗ—пјҹиҝҳжҳҜд»ҺеҪ“еүҚеҫӘзҺҜиҝӯд»Јдёӯ (continue) и·іеҮәпјҹжҲ–иҖ…жҳҜд»Һж•ҙдёӘеҫӘзҺҜ (break) дёӯи·іеҮәпјҹ - user558061
@user558061 跳出整个循环并进入下一次迭代。 - Shashank Singh
@MartijnPieters 我看到一些关于 Python 很长时间没有三元运算符的文章,因为它不够“Pythonic”。这让我想起了“continue”或其他从“C”继承的代码结构。 - Shashank Singh
@Shashank 嗯,语言在不断发展 - 就我个人而言,我认为 Python 中实现的三元运算符相当 Pythonic,肯定比滥用 or 的旧方法要好得多。 - Voo
4个回答

9
如果在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() 

这是正确的答案(如果我们回答标题中的问题而不是描述中的问题)。continue用于跳出当前循环迭代并开始下一次迭代。如果您只想退出try/except块,而且在tryexcept块内没有任何操作,则pass是正确的关键字。回答您(OP)的问题,““continue”是从try catch块中逃脱的Pythonic方式吗?”,那么如果您在块中没有做任何事情,那么pass是正确的方式。 - user558061

3

这正是continue/break关键字的用途,所以是最简单和最pythonic的方法。

最好只有一种——而且最好是唯一明显的方法。


2

您应该使用

try:
    element = location.objects.order_by('-id').filter(name__id=idRef)[0]
except IndexError:
    pass

1

你让人有点难以理解你在做什么。这段代码只是检查查询结果是否有任何行,通过查看第一个元素并捕获IndexError。

我会以一种更清晰的方式编写它:

for locationName in locationGroup:
    idRef = locationName.id
    rows = location.objects.order_by('-id').filter(name__id=idRef)
    if rows: # if we have rows do stuff otherwise continue
         element = rows[0]
         ...

在这种情况下,您可以使用{{link1:get}},这使得它更加清晰:
for locationName in locationGroup:
    idRef = locationName.id
    try:
         element = location.objects.get(name__id=idRef)
    except location.DoesNotExist:
         pass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接