我想检查变量是否存在。现在我在做这样的事情:

try:
    myVar
except NameError:
    # Do something.

有没有其他没有例外的方法?


当前回答

像这样:

def no(var):
    "give var as a string (quote it like 'var')"
    assert(var not in vars())
    assert(var not in globals())
    assert(var not in vars(__builtins__))
    import keyword
    assert(var not in keyword.kwlist)

之后:

no('foo')
foo = ....

如果你的新变量foo使用起来不安全,你会得到一个AssertionError异常,它会指向失败的行,然后你就知道了。 这是一个明显做作的自我指涉:

no('no')

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-88-d14ecc6b025a> in <module>
----> 1 no('no')

<ipython-input-86-888a9df72be0> in no(var)
      2     "give var as a string (quote it)"
      3     assert( var not in vars())
----> 4     assert( var not in globals())
      5     assert( var not in vars(__builtins__))
      6     import keyword

AssertionError: 

其他回答

它可能不是高性能的,但您将解决方案泛化为一个同时检查局部变量和全局变量的函数。

import inspect
def exists_var(var_name):
    frame = inspect.currentframe()
    try:
        return var_name in frame.f_back.f_locals or var_name in globals()
    finally:
        del frame

然后你可以这样使用它:

exists_var('myVar')

我创建了一个自定义函数。

def exists(var):
     return var in globals()

然后调用函数,将variable_name替换为你想检查的变量:

exists("variable_name")

将返回True或False

catch被调用,除非在Python中。除此之外,对于这种简单的情况,它是可以接受的。AttributeError可以用来检查对象是否有属性。

对象也可以使用__dict__。

class A(object):
    def __init__(self):
        self.m = 1

a = A()
assert "m" in a.__dict__
assert "k" not in a.__dict__

像这样:

def no(var):
    "give var as a string (quote it like 'var')"
    assert(var not in vars())
    assert(var not in globals())
    assert(var not in vars(__builtins__))
    import keyword
    assert(var not in keyword.kwlist)

之后:

no('foo')
foo = ....

如果你的新变量foo使用起来不安全,你会得到一个AssertionError异常,它会指向失败的行,然后你就知道了。 这是一个明显做作的自我指涉:

no('no')

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-88-d14ecc6b025a> in <module>
----> 1 no('no')

<ipython-input-86-888a9df72be0> in no(var)
      2     "give var as a string (quote it)"
      3     assert( var not in vars())
----> 4     assert( var not in globals())
      5     assert( var not in vars(__builtins__))
      6     import keyword

AssertionError: