python – How else can you set the default value of a variable other than try-except?


The obj object is an instance of some kind of django model. Let's say it has a prop field, which is supposed to be associated with another model, but could also be None . My task is to write to the var variable the target field of the second linked model.

var =

If the prop field is equal to None , then everything will break, since None does not have a target field. In this case, I want to set the var variable to None . Basically I can do it like this

    var =
except AttributeError:
    var = None

Is there some other way to do this, like setdefault for dictionaries?


Use the built-in function getattr(object, name[, default]) :

var = getattr(obj.prop, "target", None)

Excerpt from documentation :

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a
string. If the string is the name of one of the object’s attributes,
the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not
exist, default is returned if provided, otherwise AttributeError is

Scroll to Top