Search code examples
pythonpep8

Is it pythonic to use shortcut expression instead of ternary?


I often use the ternary operator in python and it works great :-) Now i've seen that it would be possible to use the 'or' operator for most of that cases. For example:

# Ternary operator example
class Foo:
    first = 'First'
    second = 'Second'
    def bar(self):
        return self.first if self.first else self.second


foo=Foo()
foo.bar()  # returns 'First'

foo.first = None
foo.bar()  # returns 'Second'

The same functionality could be achieved using the 'or'-operator as a Short-cirquit evaluation.

# Short-cirquit evaluation
class Foo:
    first = 'First'
    second = 'Second'
    def bar(self):
        return self.first or self.second


foo=Foo()
foo.bar()  # returns 'First'

foo.first = None
foo.bar()  # returns 'Second'

Now the question:

Would the usage of the Short-cirquit evaluation be considered as pep-8 and pythonic usage or is it not explicit enough? Is it accepted as a professional solution?


Solution

  • Yes, it's perfectly reasonable to use short-circuit with either or or and. The important part is that the resulting code should be the most readable and maintainable version you can make. For instance, when I crawl down a list of get references, I'll do something like

    return obj and obj.record and obj.record.field_I_want
    

    This does a nice job of giving me None when anything in the reference sequence doesn't exist, but returns the field value if everything is healthy.