检查某些东西是否存在的 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'
如果我只关心 kn 有没有办法在没有 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屋!