Search code examples
pythonexpressiondefault

Short way to write if exists else


What I want to do is :

if myObject:  # (not None)
    attr = myObject.someAttr
else:
    attr = ''

And avoiding if possible, ternary expressions. Is there something like :

attr = myObject.someAttr || '' ? 

I was thinking of creating my own function such as :

get_attr_or_default(instance,attr,default):
    if instance:
        return instance.get_attribute(attr)
    else:
        return default

But I would be surprised to hear that python doesn't have a shortcut for this.

Synthesis :

I tried both of solutions and here's the result :

class myClass(Models.model):
    myObject = model.foreignKey('AnotherClass')

class AnotherClass(Models.model):
    attribute = models.charField(max_length=100,default = '')


attr = myClass.myObject.attribute if myClass.myObject else '' # WORKED
attr = myClass.myObject and myClass.myObject.attribute # WORKED with NONE as result
attr = myClass.myObject.attribute or ''  # Raises an error (myObject doesn't have attribute attribute)
try: attr = myClass.myObject.attribute
except AttributeError: attr = ''  # Worked

Thanks for your answers !


Solution

  • 6.11. Conditional expressions

    attr = myObject.someAttr if myObject else ""