1
----> 1 if person.network is None:
      2     print('person.network does not exist')
      3 

AttributeError: 'Person' object has no attribute 'network'

As you can see on line 1, I'm checking if 'network' doesn't exist. However, when it doesn't exist it fails and throws a python error. I'm a bit lost as to how this is happening. Shouldn't line 1 catch this exact problem?

The actual code properly goes through about 10 records before failing when one of them doesn't have 'network' defined.

mauvehed
  • 45
  • 1
  • 7

2 Answers2

3

You can use the built in python function hasattr :

    if hasattr(person, "network") : 
Dflip240
  • 115
  • 1
  • 7
3

There is a difference between an instance attribute having the value of None and it not existing at all (your case). To properly check whether an instance attribute exist, you can use the hasattr() method:

if hasattr(person, "network"):
    # do stuff

If you need to retrieve the value, you can do so safely using getattr():

network = getattr(person, "network", None)

The last parameter is the default value to be returned in case person does not have the network attribute.

bow
  • 2,503
  • 4
  • 22
  • 26