开发者

How do I test if a variable that I declared in an inner block exists in the outer block?

开发者 https://www.devze.com 2023-02-10 10:21 出处:网络
Given this sample Python code: for item in items: if somecondition(item): requireditem = item break # use item

Given this sample Python code:

for item in items:
    if somecondition(item):
        requireditem = item
        break

# use item

How can I know if I'm allowed to access requireditem after the loop? i.e. if somecondition(item) was True for some item in the list.

One solution might be:

requireditem = None

for item in items:
    if somecondition(item):
        requireditem = item
        break

if requiredit开发者_高级运维em != None:
    # do something

But I'm wondering what's the Pythonic way of doing this.


Are you doing anything else in the loop? Are you setting somevar to anything besides True? If not, perhaps this would be better:

if any(somecondition(item) for item in items):
    # do something

There's no real need for a variable.

From your edit:

There's still a better way to do this:

required_items = [item for item in items if somecondition(item)]
if required_items:
    # do something
    # if only one required item is ever present, then maybe...
    required_item = required_items[0]


You can try something like this (but was your question more related to variable scoping?)

somevar = [item for item in items if somecondition(item)]

if somevar:
    do something


What you are referring to is called "variable scope".

Here is a nice article that explains it well for new programmers. http://www.digital-web.com/articles/variable_scope_for_new_programmers/


If you really want to know if there is a way to test if the local variable exists, you can do so by handling the UnboundLocalError exception:

try:
    somevar
except UnboundLocalError:
    print "Variable does not exist"
else:
    print "Variable exists"

But this is certainly not considered "pythonic". Don't do that. Either set the variable to None beforehand or use a different approach altogether.

One solution would be to make use of Python's for-else construct:

for item in items:
   if somecondition(item):
       break
else:
   raise NoSuitableItemFound()  # If no break occurred.


For the minimum change to your code, just do whatever it is you want to do in the loop body and then break out. You should probably be breaking out on the first match anyway (unless you want to always scan the entire list and need the last item satisfying your condition).

for item in items:
    if somecondition(item):
        # do something with item
        break

However, there are better ways to do this depending on exactly what you want to do (others have posted such solutions).


For the edited question, you could use

try:
    requireditem = next(item for item in items if somecondition(item))
except StopIteration:
    # error handling, no item found
else:
    # do something with requireditem

This will traverse items only until the first matching item is found, in contrast to the solutions using a list comprehension.

0

精彩评论

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