用pythonic方式检查是否存在某些东西? [英] pythonic way to check if something exists?
问题描述
这是非常基本但我编码并开始想知道是否有一种pythonic方法来检查是否存在某些东西。如果它是真的,我就是这样做的:
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:
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'
如果所有我关心的都是knis那么看起来就像浪费在没有else的情况下检查是否存在某些东西的方法?
Seems like a waste if all I care about is knIs there a way to check if something does not exist without the else?
推荐答案
LBYL风格,在你跳跃之前看:
LBYL style, "look before you leap":
var_exists = 'var' in locals() or 'var' in globals()
EAFP风格,比允许更容易请求宽恕:
EAFP style, "easier to ask forgiveness than permission":
try:
var
except NameError:
var_exists = False
else:
var_exists = True
在Python编码时首选第二种样式(EAFP),因为它通常更可靠。
Prefer the second style (EAFP) when coding in Python, because it is generally more reliable.
这篇关于用pythonic方式检查是否存在某些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!