Home > Software design >  Catching NoneType bugs using isinstance
Catching NoneType bugs using isinstance

Time:07-07

I have below code but not isinstance() isn't working as expected.

<ipython-input-94-009e9fb4f54a> in extract(self, row)
     34             event_payload_json = json.loads(row.event_payload)
     35             #print(event_payload_json['payload']['info']['work'])
---> 36             if not isinstance(event_payload_json['payload']['info']['work'], type(None)):
     37                 if "test_statement" not in event_payload_json['payload']['info']['work']:
     38                     decoded_str = base64.b64decode(<>)

TypeError: 'NoneType' object is not subscriptable

My intention is exactly to not decode if event_payload_json['payload']['info']['work'] not NoneType, however it's not working as expected. Any help would be appreciated!

CodePudding user response:

In Python None is a singleton so can just do:

if event_payload_json['payload']['info']['work'] is not None:

Also if event_payload_json['payload']['info']['work'] only takes truthy values then it would be enough to check it like this

if event_payload_json['payload']['info']['work']:

CodePudding user response:

The error tells you that you tried to subscript None, so either event_payload_json['payload'] or event_payload_json['payload']['info'] is None. The easiest way to handle that error is to put the statement in a try/except block and catch the TypeError. It turns out that attempting to see if a string is in None is also a TypeError, so you can handle all of your cases all at once.

event_payload_json = json.loads(row.event_payload)
#print(event_payload_json['payload']['info']['work'])
try:
    work = event_payload_json['payload']['info']['work']
    if "test_statement" not in work:
        decoded_str = base64.b64decode(work)
except TypeError:
    pass
  • Related