TheBigOnion
TheBigOnion

Reputation: 625

How to catch - 'NoneType' object has no attribute 'something'

I Know what the error:

AttributeError: 'NoneType' object has no attribute 'something'

means, but what I cannot figure out is how to catch it. Basically i want to check to see if my object is created or not.

I want to do something like this:

try:
    test = self.myObject.values()
except:
    print "Error happened"

But every time I do I get:

AttributeError: 'NoneType' object has no attribute 'values'

Can someone tell me how to catch this?

Upvotes: 10

Views: 25011

Answers (2)

Moshe Carmeli
Moshe Carmeli

Reputation: 295

you can use the hasattr(object, name) method which returns True or False. If you try to access an attribute which does not exist you will always receive an exception. https://docs.python.org/2/library/functions.html#hasattr

If you still wish to catch the exception then simply do a try/catch block with exception type 'AttributeError'

Upvotes: 8

aruisdante
aruisdante

Reputation: 9075

There are a number of ways to do this. If you just want to see if an object exists, you can do:

if self.myObject:
    # do stuff with my object
else:
    # do other stuff

#Or the more explicit form, if myObject could be 'falsey' normally, like an empty list/dict
if self.myObject is not None:

If you can assign a reasonable default, you can one-line this like so

test = self.myObject.something if self.myObject else default_value

Where default_value is whatever you can use as a reasonable default. Thanks to python's short circuit evaluation, this is safe, as the self.myObject.something will never be evaluated if self.myObject is None (or falsey).

Upvotes: 5

Related Questions