开发者

How can this behavior be acomplished? Python "short circuting" test

I have the following code:

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    for x in geodatabaseList:
        if x == self.outputGeodatabase:
            return True
        else:
            pass
    return False

What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    for x in geodataba开发者_JAVA百科seList:
        if x == self.outputGeodatabase:
            return True
            break
        else:
            pass
    return False

If the following code does not solve my problem, what can i use to do simulate that behavior?

Thanks


return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as

def testGeodatabase(self):
    return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")


You don't need the break keyword in the code above. Actually, you don't need the

else:
   pass

either. The

return True

will exit the function.


The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.

Here is a simple test which you could run to prove the point:

def someFunction(nums):
    for i in nums:
        if i == 1:
            return "Found 1!"
    return "Never found 1"

And running it:

>>> someFunction([2])  
'Never found 1'  
>>> someFunction([2,1,3])  
'Found 1!'  


I think that using any() is the best choice:

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    return any(x == self.outputGeodatabase for x in geodatabaseList)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜