Home > database >  TypeError 'NoneType' even after a typecheck python 3.8
TypeError 'NoneType' even after a typecheck python 3.8

Time:10-09

I'm getting a TypeError: 'NoneType' object is not iterable even after checking type


print(type(order))
print(len(order))
if type(order['shipmentItems']) is not None:
   for item in order['shipmentItems']: # ----- errors here


the for loop iterates through once through before calling the error

CodePudding user response:

Simply test if my_object is not None, not if type(my_object) is not None

>>> type(None) is None
False
>>> type(None)
<class 'NoneType'>  # Python 3.9.x

This is effectively the comparison that you're making, which will never be True.

You can also use:

for item in order.get('shipmentItems', []):

to simplify instead, iterating over an empty list if the key is missing, or the key is present but the value is falsey.

Reproduction of where you're getting tripped up:

>>> order = {}
>>> order['shipmentItems'] = None
>>> type(order['shipmentItems']) is not None
True
>>> order['shipmentItems'] is not None
False
  • Related