How do we get an optional class attribute in Python?

python

Solution

You can use `hasattr` and `getattr`.

For example:

hasattr(foo, 'bar')

would return `True` if `foo` has an attribute named `bar`, otherwise `False` and

getattr(foo, 'bar', 'quux')

would return `foo.bar` if it exists, otherwise defaults to `quux`.

Problem

For dictionary we can use `.get` method. What about a class's attribute and provide a default value?

Original source