I am running some python3 code which will occasionally get a list, dict, and None.
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
print('fieldType=')
print(fieldType)
if fieldType is None:
print('its none')
else:
print('its not none')
this works for everything except when fieldType is 'None':
fieldType=
<class 'collections.OrderedDict'>
its not none
#this output works as expected
but when fieldType is <class 'NoneType'>
it reports it as being 'not none'
fieldType=
<class 'NoneType'>
its not none
why cant my code correctly identify when an object is of type 'None'?
CodePudding user response:
fieldType
is <class 'NoneType'>
, which is different from None
. It can never be None
, because type
always returns some type.
Looks like you want
raw_data[root_key].get("oslc_cm:ChangeRequest") is None
instead of
fieldType is None
CodePudding user response:
None != type(None)
type(None)
is a <class 'type'>
object. The correct way to chech a type of a variable in python is to use isinstance()
. Then your code would look like this:
NoneType = type(None)
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
print('fieldType=')
print(fieldType)
if isinstance(fieldType, NoneType):
print('its none')
else:
print('its not none')
CodePudding user response:
This is a common mistake. The proper way to test for a value being None is to use is or is not, not using equality tests:
if fieldType is None:
print('its none')
else:
print('its not none')
the get()
method returns None
(and hence evaluates to False
) when there are no items in the dictionary. This means you'd get the same result by using if not raw_data[root_key].get("oslc_cm:ChangeRequest")
: which means "if there's no entry for oslc_cm:ChangeRequest in raw_data[root_key]
". Because of this, you can write your code like this instead:
fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest"))
if fieldType is not None:
print('its not none')
else:
print('its none')