用pythonic方式检查是否存在某些东西? [重复]

时间:2022-03-11 22:37:53

This question already has an answer here:

这个问题在这里已有答案:

This is pretty basic but I was coding and started wondering if there was a pythonic way to check if something does not exist. Here's how I do it if its true:

这是非常基本的,但我编码并开始想知道是否有一种pythonic方法来检查是否存在某些东西。这是我如何做到的,如果它是真的:

var = 1
if var:
    print 'it exists'

but when I check if something does not exist, I often do something like this:

但是当我检查是否存在某些东西时,我经常这样做:

var = 2
if var:
    print 'it exists'
else:
    print 'nope it does not'

Seems like a waste if all I care about is knIs there a way to check if something does not exist without the else?

如果我所关心的只是一种浪费,似乎是一种浪费,如果没有其他东西,有没有办法检查是否存在某些东西?

6 个解决方案

#1


97  

LBYL style, "look before you leap":

LBYL风格,“在你跳跃之前看”:

var_exists = 'var' in locals() or 'var' in globals()

EAFP style, "easier to ask forgiveness than permission":

EAFP风格,“比允许更容易请求宽恕”:

try:
    var
except NameError:
    var_exists = False
else:
    var_exists = True

Prefer the second style (EAFP) when coding in Python, because it is generally more reliable.

在Python中编码时首选第二种样式(EAFP),因为它通常更可靠。

#2


19  

I think you have to be careful with your terminology, whether something exists and something evaluates to False are two different things. Assuming you want the latter, you can simply do:

我认为你必须小心你的术语,无论是否存在某种东西,并且评估为False的东西是两个不同的东西。假设你想要后者,你可以简单地做:

if not var:
   print 'var is False'

For the former, it would be the less elegant:

对于前者,它将不那么优雅:

try:
   var
except NameError:
   print 'var not defined'

I am going to take a leap and venture, however, that whatever is making you want to check whether a variable is defined can probably be solved in a more elegant manner.

然而,我想进行一次飞跃和冒险,无论你想要检查变量是否被定义,都可以以更优雅的方式解决。

#3


2  

To check if a var has been defined:

要检查是否已定义var:

var = 2

try: 
    varz
except NameError:
    print("No varz")

To check if it is None / False

检查它是否为None / False

if varz is None

...or

...要么

if not varz

#4


2  

If this is a dictionary, you can have

如果这是一本字典,你可以拥有

mydict['ggg'] = ''   // doesn't matter if it is empty value or not.
if mydict.has_key('ggg'):
   print "OH GEESH"

However, has_key() is completely removed from Python 3.x, therefore, the Python way is to use in

但是,has_key()已从Python 3.x中完全删除,因此,Python的方式是使用

'ggg' in mydict     # this is it!
# True if it exists
# False if it doesn't

You can use in for tuple, list, and set as well.

您也可以使用in进行元组,列表和设置。


Of course, if the variable hasn't been defined, you will have to raise an exception silently (just raise any exception... let it pass), if exception is not what you want to see (which is useful for many applications, you just need to log the exception.)

当然,如果尚未定义变量,则必须以静默方式引发异常(只是引发任何异常......让它通过),如果异常不是您想要看到的(这对许多应用程序很有用,你只需要记录异常。)


It is always safe to define a variable before you use it (you will run into "assignment before local reference" which means " var is not in the scope " in plain English). If you do something with query, the chance is, you will want to have a dictionary, and checking whether a key exists or not, use in .

在使用它之前定义一个变量总是安全的(你将遇到“在本地引用之前赋值”,这意味着“var不在范围内”,用简单的英语表示)。如果您对查询执行某些操作,则可能需要使用字典,并检查密钥是否存在,请使用。

#5


0  

What about the negation?

否定呢?

if not var:
    print 'nope it does not'

Though this is to see if the var is false / none and would blow up if var is not defined.

虽然这是为了查看var是否为false / none,如果未定义var,则会爆炸。

To see if var is defined:

要查看var是否已定义:

try:
    var
except NameError:
    print 'not defined'

#6


0  

if not var:
    #Var is None/False/0/

if var:
    #Var is other then 'None/False/0'

in Python if varibale is having any value from None/False/0 then If var condition will fail...

在Python中,如果varibale具有None / False / 0中的任何值,则if var condition将失败...

and for other objects it will call __nonzero__ pythonic method which may return True or False depending on its functionality.

对于其他对象,它将调用__nonzero__ pythonic方法,该方法可能会根据其功能返回True或False。

#1


97  

LBYL style, "look before you leap":

LBYL风格,“在你跳跃之前看”:

var_exists = 'var' in locals() or 'var' in globals()

EAFP style, "easier to ask forgiveness than permission":

EAFP风格,“比允许更容易请求宽恕”:

try:
    var
except NameError:
    var_exists = False
else:
    var_exists = True

Prefer the second style (EAFP) when coding in Python, because it is generally more reliable.

在Python中编码时首选第二种样式(EAFP),因为它通常更可靠。

#2


19  

I think you have to be careful with your terminology, whether something exists and something evaluates to False are two different things. Assuming you want the latter, you can simply do:

我认为你必须小心你的术语,无论是否存在某种东西,并且评估为False的东西是两个不同的东西。假设你想要后者,你可以简单地做:

if not var:
   print 'var is False'

For the former, it would be the less elegant:

对于前者,它将不那么优雅:

try:
   var
except NameError:
   print 'var not defined'

I am going to take a leap and venture, however, that whatever is making you want to check whether a variable is defined can probably be solved in a more elegant manner.

然而,我想进行一次飞跃和冒险,无论你想要检查变量是否被定义,都可以以更优雅的方式解决。

#3


2  

To check if a var has been defined:

要检查是否已定义var:

var = 2

try: 
    varz
except NameError:
    print("No varz")

To check if it is None / False

检查它是否为None / False

if varz is None

...or

...要么

if not varz

#4


2  

If this is a dictionary, you can have

如果这是一本字典,你可以拥有

mydict['ggg'] = ''   // doesn't matter if it is empty value or not.
if mydict.has_key('ggg'):
   print "OH GEESH"

However, has_key() is completely removed from Python 3.x, therefore, the Python way is to use in

但是,has_key()已从Python 3.x中完全删除,因此,Python的方式是使用

'ggg' in mydict     # this is it!
# True if it exists
# False if it doesn't

You can use in for tuple, list, and set as well.

您也可以使用in进行元组,列表和设置。


Of course, if the variable hasn't been defined, you will have to raise an exception silently (just raise any exception... let it pass), if exception is not what you want to see (which is useful for many applications, you just need to log the exception.)

当然,如果尚未定义变量,则必须以静默方式引发异常(只是引发任何异常......让它通过),如果异常不是您想要看到的(这对许多应用程序很有用,你只需要记录异常。)


It is always safe to define a variable before you use it (you will run into "assignment before local reference" which means " var is not in the scope " in plain English). If you do something with query, the chance is, you will want to have a dictionary, and checking whether a key exists or not, use in .

在使用它之前定义一个变量总是安全的(你将遇到“在本地引用之前赋值”,这意味着“var不在范围内”,用简单的英语表示)。如果您对查询执行某些操作,则可能需要使用字典,并检查密钥是否存在,请使用。

#5


0  

What about the negation?

否定呢?

if not var:
    print 'nope it does not'

Though this is to see if the var is false / none and would blow up if var is not defined.

虽然这是为了查看var是否为false / none,如果未定义var,则会爆炸。

To see if var is defined:

要查看var是否已定义:

try:
    var
except NameError:
    print 'not defined'

#6


0  

if not var:
    #Var is None/False/0/

if var:
    #Var is other then 'None/False/0'

in Python if varibale is having any value from None/False/0 then If var condition will fail...

在Python中,如果varibale具有None / False / 0中的任何值,则if var condition将失败...

and for other objects it will call __nonzero__ pythonic method which may return True or False depending on its functionality.

对于其他对象,它将调用__nonzero__ pythonic方法,该方法可能会根据其功能返回True或False。