How do I check if a variable exists?

后端 未结 11 1988
野的像风
野的像风 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:40

    Short variant:

    my_var = some_value if 'my_var' not in globals() else my_var:
    
    0 讨论(0)
  • 2020-11-22 02:43

    Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.

    For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:

    my_variable = None
    
    def InitMyVariable():
      global my_variable
      if my_variable is None:
        my_variable = ...
    
    0 讨论(0)
  • 2020-11-22 02:47

    for objects/modules, you can also

    'var' in dir(obj)
    

    For example,

    >>> class Something(object):
    ...     pass
    ...
    >>> c = Something()
    >>> c.a = 1
    >>> 'a' in dir(c)
    True
    >>> 'b' in dir(c)
    False
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:53

    catch is called except in Python. other than that it's fine for such simple cases. There's the AttributeError that can be used to check if an object has an attribute.

    0 讨论(0)
  • 2020-11-22 02:54

    A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:

    # Search for entry.
    for x in y:
      if x == 3:
        found = x
    
    # Work with found entry.
    try:
      print('Found: {0}'.format(found))
    except NameError:
      print('Not found')
    else:
      # Handle rest of Found case here
      ...
    
    0 讨论(0)
提交回复
热议问题