1

I like using the is None test for empty variables, it's very flexible, easy and useful. It seems to have stopped working now:

>"" is None
False

>[] is None
False

>{} is None
False

What's going on?

I'm using Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5], on Debian/Sid i686 GNU/Linux.

Edit: Awesome tip from Sven Marnach of using bool(""). brb, off to edit some code...

1
  • 4
    This never should have worked...is None isn't for testing empty variables, it's for testing precisely if they are None. Commented Jun 27, 2011 at 18:22

5 Answers 5

7

The test x is None tests if x really is the None object (that is, if the name x references the object None). What you are looking for is truth value testing:

if "":
    print "non-empty"
else:
    print "empty"

if implicitly converts the condition to bool. You can also explicitly do this:

>>> bool("")
False
>>> bool("x")
True
Sign up to request clarification or add additional context in comments.

Comments

2

Um... that never worked. is tests for instance identity -- even {} is {} is false.

>>> {} is {}
False

Comments

1

Only None is None. I think what you are looking for is the boolean values of the empty list, dict, and str

For example:

>>> if "":
...     print 'woo'
... else:
...     print 'hoo'
...
hoo

Same for {} and []

Comments

1

It was never working. Only None is None is True.

Comments

0

If you want to simply check on empty values it is better to use the following:

a = {}
b = []
c = ""

if a:
    print 'non-empty dict'
else:
    print 'empty dict'

if b:
    print 'non-empty list'
else:
    print 'empty list'

if c:
    print 'non-empty string/value'
else:
    print 'empty string/value'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.