What is universal method for `get or default` in python?


I would like to get an attribute of mongoengine model object but it’s missing (how it’s often in mongo):

unit.city gives me AttributeError

unit.get('city') says that 'Unit' object has no attribute 'get' and I can’t find any appropriate method by dir(unit).

So I have to use standard python statement:

city = unit.city if 'city' in unit else None

That is a bit complex for just a get operation, because I have many transformations of that kind.

And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn’t exist) — such as get for dict type:

city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'

I would define my own function get but I’m interested if there is any in standard libraries. And yet, from operation import getitem doesn’t able to do that.

I use python 2, by the way.

Asked By: egvo



There is getattr(object, name[, default]):

city = getattr(unit, 'city', 'Moscow')
Answered By: Dan D.

In general python, there are two common patterns. A mix of hasattr + getattr or wrapping the whole thing in try / except

city = getattr(unit,'city','Moscow')

Other approach is

    city = unit.city
except AttributeError:
    city = None

The second is argubly more pythonic. However when you are dealing with databases. It’s better to use an ORM and avoid this sort of thing all together.

Answered By: e4c5