How do I check if a variable exists?

后端 未结 11 2206
野的像风
野的像风 2020-11-22 02:09

I want to check if a variable exists. Now I\'m doing something like this:

try:
   myVar
except NameError:
   # Do something.

Are there othe

11条回答
  •  情书的邮戳
    2020-11-22 02:51

    This was my scenario:

    for i in generate_numbers():
        do_something(i)
    # Use the last i.
    

    I can’t easily determine the length of the iterable, and that means that i may or may not exist depending on whether the iterable produces an empty sequence.

    If I want to use the last i of the iterable (an i that doesn’t exist for an empty sequence) I can do one of two things:

    i = None  # Declare the variable.
    for i in generate_numbers():
        do_something(i)
    use_last(i)
    

    or

    for i in generate_numbers():
        do_something(i)
    try:
        use_last(i)
    except UnboundLocalError:
        pass  # i didn’t exist because sequence was empty.
    

    The first solution may be problematic because I can’t tell (depending on the sequence values) whether i was the last element. The second solution is more accurate in that respect.

提交回复
热议问题