Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if object has attributes?

Tags:

python

 if groupName.group == "None":

error:

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

How to check if object has an attribute?

like image 458
J.Olufsen Avatar asked Dec 01 '22 01:12

J.Olufsen


2 Answers

You want getattr(), which you can pass a default value, or hasattr().

like image 200
a paid nerd Avatar answered Dec 05 '22 03:12

a paid nerd


The error message is telling you that groupName itself is None.

In which case, there's little point in testing whether it has a particular attribute.

So you probably want something more like:

If groupName is not None:
    print groupName.group

Or, if groupName objects may not have a group attribute:

If groupName is not None:
    print getattr(groupName, 'group', None)

(Note: the last argument of getattr is a default value that can be anything you want).

like image 40
ekhumoro Avatar answered Dec 05 '22 02:12

ekhumoro