Is there any expression in python similar to ruby ​​|| =

I found an interesting expression in Ruby:

a ||= "new"

This means that if a is not defined, a "new" value will be assigned to a; otherwise a will be the same as it. This is useful when executing some database query. If the value is set, I do not want to run another database query.

So, I tried similar thinking in Python:

a = a if a is not None else "new"

Failed. I think this is because you cannot do "a = a" in Python if a is not defined.

So, the solutions I can execute check locals () and globals () or use try ... except expression:

myVar = myVar if 'myVar' in locals() and 'myVar' in globals() else "new"

or

try:
    myVar
except NameError:
    myVar = None

myVar = myVar if myVar else "new"

As we can see, the solutions are not so elegant. So I would like to ask if there is a better way to do this?

+5
source share
6

?

try:
    a = a
except NameError:
    a = "new"

, ( ) .

+3

undefined " " - . , , a = a, . (, None), . , . , , uninitalized " " "" , . , :

 # code with no initialization. . .
 a ||= blah

:

a = None
# code
if a is None:
    a = blah
+5

, Python dict, : d.get('a', 'new'). , globals()/locals(). get('a', 'new'), - Python - , - (, None).

globals() setdefault()

>>> a
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> globals().setdefault('a', 'new')
'new'
>>> a
'new'
>>> a = 'old'
>>> globals().setdefault('a', 'new')
'old'
>>> a
'old'
+1

Pythonic - , , , / vars, , . , pythonic

a = None
# other codes
a = a or 'new'

+1

memoization, Pythonic. Python 2:

# Backport of Python 3 lru_cache
# pip install functools32
from functools32 import lru_cache

@lru_cache()
def expensive_db_query(arg):
    print "Running expensive db query for", arg
    return arg[::-1]

expensive_db_query("spam") # prints "Running expensive db query for spam"
expensive_db_query("spam") # No output
expensive_db_query("eggs") # prints "Running expensive db query for eggs"

If you want the cache to forget the values ​​after enough time has passed and query the database again, check the Ilialuk lru cache .

+1
source

Here's an option inspired by this answer on how to check if a variable is defined:

a = a if "a" in vars() or "a" in globals() else "new"

This is not so short, but it is at least one line.

In [1]: a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-60b725f10c9c> in <module>()
----> 1 a

NameError: name 'a' is not defined

In [2]: a = a if "a" in vars() or "a" in globals() else "new"

In [3]: a
Out[3]: 'new'

In [4]: a = "A exists!"

In [5]: a = a if "a" in vars() or "a" in globals() else "new"

In [6]: a
Out[6]: 'A exists!'

However, I agree with BrenBarn that you should avoid the problem with the undefined variable by simply declaring it with a a=Nonebefore block where you cannot set it.

0
source

All Articles