5

I know that comparison of types is not recommended, but I have some code that does this in an if elif series. However, I am confused as to how None values work.

def foo(object)
    otype = type(object)
    #if otype is None: # this doesn't work
    if object is None: # this works fine
        print("yep")
    elif otype is int:
    elif ...

How come I can compare just fine with is int and so forth, but not with is None? types.NoneType seems to be gone in Python 3.2, so I can't use that...

The following

i = 1
print(i)
print(type(i))
print(i is None)
print(type(i) is int)

prints

1
<class 'int'>
False
True

whereas

i = None
print(i)
print(type(i))
print(i is None)
print(type(i) is None)

prints

None
<class 'NoneType'>
True
False

I guess None is special, but what gives? Does NoneType actually exist, or is Python lying to me?

0

2 Answers 2

10

None is a special-case singleton provided by Python. NoneType is the type of the singleton object. type(i) is None is False, but type(i) is type(None) should be true.

7

You should never need to compare to NoneType, because None is a singleton. If you have some object obj that might be None, just is obj is None or obj is not None.

The reason your comparison does not work is that None is not a type, it is a value. It would similar to trying type(1) is 1 in your integer example. If you really wanted to do a NoneType check, you could use type(obj) is type(None), or better yet isinstance(obj, type(None)).

4
  • Very true and important, but the other parts of the question deserve an answer too.
    – user395760
    Nov 5, 2012 at 19:13
  • Which makes checking None-ness a special case in any type-checking code. Sometimes, it is cleaner to check for NoneType than to check x is None or isinstance(x, (footype, bartype)).
    – Silas Ray
    Nov 5, 2012 at 19:14
  • 4
    Object identity is actually the right thing for checking for a type: type(obj) is SomeType is what I recommend for checking for exact type matches (a very rare requirement). In the common case, use isinstance(). Nov 5, 2012 at 19:22
  • @SvenMarnach Good to know! For some reason I thought type checking called for a value comparison. Nov 5, 2012 at 20:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.