How to Know If an Object has an Attribute in Python

Created
Modified

Using hasattr Method

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

class Person:
  age = 10

person = Person()
print(hasattr(person, "name"))
False

Using AttributeError Exception

Raised when an attribute reference or assignment fails.

For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

class Person:
  age = 10

person = Person()
try:
  person.name
  # Exists
except AttributeError:
  # Doesn't exist
  print("Doesn't exist")
Doesn't exist

Using in Keyword

This approach has serious limitation. in keyword works for checking iterable types.

For example,

person = {
  "age": 10
}
if 'age' in person:
  print(person['age'])
10

Using dir Method

The method dir() returns a list of valid attributes for that object. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

#!/usr/bin/python3
# -*- coding: utf8 -*-

class Person:
  age = 10

person = Person()
if 'age' in dir(person):
  print(person.age)
10

Related Tags