What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working?
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 return
statement on two different lines:
def get_foo(self):
self._foo = self._foo or Bar()
return self._foo
But in general, it's better to write it out:
def get_foo(self):
if not self._foo:
self._foo = Bar()
return self._foo
Python's assignment operator doesn't pass through the assigned value, primarily because in other languages it has proven to be a fruitful generator of accidental =
/==
bugs. Instead you have to be explicit:
def get_foo(self):
if self._foo is None:
self._foo= Bar()
return self._foo
You can make an expression with side-effects if you really want to:
def set_foo(self, v):
self._foo= v
return v
return self._foo or self.set_foo(Bar())
but it's generally considered a Bad Thing.
I might be wrong, but this looks like a job for the ||=
operator.
def get_foo():
return self._foo |= Bar()
My Perl is rusty at best, but ||= seems to return an R-value, so the return should work.
Edit: Woopsie, this is Python. It doesn't have a ||=
. Bummer.
Then I'd use the simulated ternary operator:
def get_foo()
self._foo = self._foo is None and Bar() or self._foo
return self._foo
Edit 2: Python has a real ternary operator. Use it instead of the above.
def get_foo()
self._foo = Bar() if self._foo is None else self._foo
return self._foo
精彩评论