2012-07-13 64 views
3

我是django的新手,想到做简单的django应用程序来了解更多信息,在代码中的一个地方,我不得不选择locationName,并在表格中获取与locationName相匹配的元素。当我开始想知道是continue逃避一个for循环最pythonic的方式?问题是否继续Pythonic逃离try catch块的方式?

代码下面给出:

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

不能得到更多的Pythonic比使用关键字的方式更有意思。 – 2012-07-13 09:45:54

+0

您想从try'/'catch'块('pass')或从当前循环迭代('continue')或从整个循环('break')? – user558061 2012-07-13 11:12:44

+0

@ user558061从整个循环转义并转到下一个迭代 – 2012-07-13 11:26:21

回答

8

如果有一些代码,你不希望以后除了得到条款执行,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() 
+0

这是正确的答案(如果我们回答标题中的问题而不是描述中的问题)。 'continue'用于跳出当前的循环迭代,并从下一次迭代开始。如果你想逃离'try' /'except'块,'pass'是正确的关键字,如果你没有在'try'或'except'块内做任何事情。 为了回答你的(OP)问题,“是”继续“Pythonic从try catch块中退出的方式吗?”,然后否,如果你没有在块中做任何事情,“pass”是正确的方法。 – user558061 2012-07-13 11:05:28

2

您应该使用

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

假设在try/except块之后有更多的代码*。 – 2012-07-13 09:46:11

3

这正是continue/break关键字是,那么是的,这是最简单,最Python的方式正在做。

应该有一个 - 最好只有一个 - 明显的方法来做到这一点。

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] 
     ... 

在这种情况下,你可以使用get这使得它更清晰的:

for locationName in locationGroup: 
    idRef = locationName.id 
    try: 
     element = location.objects.get(name__id=idRef) 
    except location.DoesNotExist: 
     pass