Paul
Paul

Reputation: 2564

Python None if check fails

def myFunc( str ):
      print "str=", str
      if str == None:
        print "str is None"
      else:
        print "str is not None, value is:", str

This function is called multiple times in my app with str being None. However sometimes, although str is None, the test fails and it prints:

str=None
str is not None, value is None

How can this happen ?

Upvotes: 2

Views: 4136

Answers (4)

rbanffy
rbanffy

Reputation: 2531

You could also use the __repr__ method to show the value:

>>> x = None
>>> print 'the value of x is', x.__repr__()
the value of x is None
>>> x = "None"
>>> print 'the value of x is', x.__repr__()
the value of x is 'None'

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613531

Check the value of str again. If your test fails then str is not the special None object. Presumably str is in fact the string 'None'.

>>> str = None
>>> str == None
True
>>> str = 'None'
>>> str == None
False
>>> print str
None

Judging from your comments, str is actually u'None' which is a string of type unicode. You can test for that like this:

>>> s = unicode('None')
>>> s
u'None'
>>> print s
None
>>> s == 'None'
True

Now, whilst you could do that, I suspect that your problem lies elsewhere. The calling code must be converting this object to a string, for example with unicode(None). It would most likely be better is the calling code only converted to string if the object is not None.

Upvotes: 2

phihag
phihag

Reputation: 288280

The string 'None' and the bytestring b'None' will both print out None, but not actually be none. Also, you can have custom classes which override their __str__ methods to return 'None', although they're actually not None.

Some aesthetic notes: Python guarantees that there'll only ever be one instance of None, so you should use is instead of ==. Also, you should not name your variable str, as that's the name of a built-in.

Try this definition:

def myFunc(s):
    if s is None:
        print('str is None')
    else:
        print('str is not None, it is %r of type %s' % (s, type(s).__name__))

Upvotes: 5

D.Shawley
D.Shawley

Reputation: 59623

Is it possible that str is bound to the string object "None" by any chance?

I would recommend using if str is None instead of ==. Not to mention, you really shouldn't be using str as a variable name.

Upvotes: 1

Related Questions