Skip to content

Python hasattr difference between 2 and 3

Background

hasattr is a python built in method, which can be used to determine whether an object has an attribute.

For example, we can check the dog object has name and age, but doesn't have gender.

Python
class Dog:
    def __init__(self):
        self.name = "dog"
        self.birth = 2020

    @property
    def age(self):
        return datetime.date.today().year - self.birth

dog = Dog()

assert hasattr(dog, 'name')
assert hasattr(dog, 'age')
assert not hasattr(dog, 'gender')

Difference between 2 and 3

The hasattr only has difference when checking a dynamic property. If the dynamic property raise exception, the hasattr have different output.

  • in python2

Any exception raised by the property will be catch by the hasattr, and it will return False.

  • in python3 It will only catch AttributeError, any other error will raise to the caller.

For example,

Python
class Dog:
    def __init__(self):
        self.name = "dog"
        self.birth = 2020

    @property
    def age(self):
        return datetime.date.today().year - self.birth

    @property
    def flyable(self):
        raise NotImplementedError

    @property
    def wing(self):
        raise AttributeError("don't has ring")

dog = Dog()


# python 2
hasattr(dog, 'flyable') == False
hasattr(dog, 'wing') == False

# python 3
hasattr(dog, 'flyable') # raise NotImplementedError
hasattr(dog, 'wing') == False

So the hasattr may have different behavior depends on the dynamic property implemented.