I’d like to do something like:
def get_foo():
return self._foo or self._foo = Bar()
I am looking for the cleanest way to do it. Is it possible with or equals?
My attempts failed:
>>> foo = None
>>> foo or 'bar'
'bar'
>>> foo
>>> foo or foo = 'bar'
File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> foo or (foo = 'bar')
File "<stdin>", line 1
foo or (foo = 'bar')
^
SyntaxError: invalid syntax
In Python, you cannot use assignments in expressions. So you have to do the assignment and the
returnstatement on two different lines:But in general, it’s better to write it out: