This question already has an answer here:
I have an object myobject
, which might return None
. If it returns None
, it won't return an attribute id
:
a = myobject.id
So when myobject is None
, the stament above results in a AttributeError
:
AttributeError: 'NoneType' object has no attribute 'id'
If myobject
is None, then I want a
to be equal to None
. How do I avoid this exception in one line statement, such as:
a = default(myobject.id, None)
Following should work:
Will also work and is clearer, IMO
If you want to solve the problem in the definition of the class of
myobject
(like in Black Diamond's answer) you can simply define__getattr__
to returnNone
:This works because
__getattr__
is only called when trying to access an attribute that does not exist, whereas__getattribute__
is always called first no matter the name of the attribute. (See also this SO post.)To try out:
in my object class you can put override
The simplest way is to use the ternary operator:
The ternary operator returns the first expression if the middle value is true, otherwise it returns the latter expression.
Note that you could also do this in another way, using exceptions:
This fits the Pythonic ideal that it's easier to ask for forgiveness than permission - what is best will depend on the situation.
You should use the
getattr
wrapper instead of directly retrieving the value ofid
.This is like saying "I would like to retrieve the attribute
id
from the objectmyobject
, but if there is no attributeid
inside the objectmyobject
, then returnNone
instead." But it does it efficiently.Some objects also support the following form of
getattr
access:As per OP request, 'deep getattr':
Simple explanation:
Reduce is like an in-place recursive function. What it does in this case is start with the
obj
(universe) and then recursively get deeper for each attribute you try to access usinggetattr
, so in your question it would be like this:a = getattr(getattr(myobject, 'id', None), 'number', None)