In Python you have the None
singleton, which acts pretty oddly in certain circumstances:
>>> a = None
>>> type(a)
<type 'NoneType'>
>>> isinstance(a,None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
So first off, <type 'NoneType'>
displays that None
is not a type, but that NoneType
is. Yet when you run isinstance(a,NoneType)
, it responds with an error: NameError: name 'NoneType' is not defined
Now, given this, if you have a function with an input default set to None
, and need to check, you would do the following:
if variable is None:
#do something
else:
#do something
what is the reason that I cannot do the following instead:
if isinstance(variable,None): #or NoneType
#do something
else:
#do something
I am just looking for a detailed explanation so I can better understand this
Edit: good application
Lets say I wanted to use isinstance
so that I can do something if variable
is a variety of types, including None
:
if isinstance(variable,(None,str,float)):
#do something
Also, if run==True in the loop header, it cannot be False on the next line. The print functions in your input statements return None , and that's why you see None before the user input. Remove the calls to print() , input will print the text anyway.
None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
Use the is operator to check if a variable is None in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .
You can try:
>>> variable = None
>>> isinstance(variable,type(None))
True
>>> variable = True
>>> isinstance(variable,type(None))
False
isinstance takes 2 arguments isinstance(object, classinfo)
Here, by passing None
you are setting classinfo
to None, hence the error. You need pass in the type.
None
is not a type, it is the singleton instance itself - and the second argument of isinstance
must be a type, class or tuple of them. Hence, you need to use NoneType
from types
.
from types import NoneType
print isinstance(None, NoneType)
print isinstance(None, (NoneType, str, float))
True True
Although, I would often be inclined to replace isinstance(x, (NoneType, str, float))
with x is None or isinstance(x, (str, float))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With