Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a default value for an attribute? [duplicate]

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) 
like image 922
alwbtc Avatar asked Feb 17 '13 16:02

alwbtc


People also ask

What is the default value of the attribute?

Easy explanation: The default value of the type attribute is “text/javascript”. You can specify this type explicitly if you want, but it is never necessary.

What are the four default values of an attribute?

There are four different types of default values you can specify for an attribute in Default: #REQUIRED—The attribute is required. #IMPLIED—The attribute is optional. #FIXED value—The attribute has a fixed value.

What is Getattr in Python?

Python getattr() Function The getattr() function returns the value of the specified attribute from the specified object.


2 Answers

You should use the getattr wrapper instead of directly retrieving the value of id.

a = getattr(myobject, 'id', None) 

This is like saying "I would like to retrieve the attribute id from the object myobject, but if there is no attribute id inside the object myobject, then return None instead." But it does it efficiently.

Some objects also support the following form of getattr access:

a = myobject.getattr('id', None) 

As per OP request, 'deep getattr':

def deepgetattr(obj, attr):     """Recurses through an attribute chain to get the ultimate value."""     return reduce(getattr, attr.split('.'), obj) # usage:  print deepgetattr(universe, 'galaxy.solarsystem.planet.name') 

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 using getattr, so in your question it would be like this:

a = getattr(getattr(myobject, 'id', None), 'number', None)

like image 192
Inbar Rose Avatar answered Oct 21 '22 13:10

Inbar Rose


The simplest way is to use the ternary operator:

a = myobject.id if myobject is not None else None 

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:

try:     a = myobject.id except AttributeError:     a = None 

This fits the Pythonic ideal that it's easier to ask for forgiveness than permission - what is best will depend on the situation.

like image 34
Gareth Latty Avatar answered Oct 21 '22 14:10

Gareth Latty