xxbidiao
xxbidiao

Reputation: 874

What is the most elegant way to handle non-existing attribute in python?

I'm pretty new to duck typing and have the following question.

Are there any better way then

try:
    what_i_want = obj.some_attr
except AttributeError: # this attribute does not exist, or something other wrong happened
    what_i_want = default_value_for_what_i_want

I would like to see something like a typical get value or None in one simple statement, something like

if(i is not None and i < 10):

Upvotes: 1

Views: 627

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43196

You can use the getattr builtin:

what_i_want = getattr(obj, 'some_attr', default_value)

Upvotes: 2

Related Questions