Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 314
TheBigOnion Avatar asked Mar 17 '15 19:03

TheBigOnion


1 Answers

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'

like image 106
Moshe Carmeli Avatar answered Nov 06 '22 00:11

Moshe Carmeli