Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python - Pythonic way to check if something exists?

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'

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

LBYL style, "look before you leap":

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...