Analogue of devar in Python -


when writing python code, find myself wanting behavior similar lisp's defvar. basically, if variable doesn't exist, want create , assign particular value it. otherwise, don't want anything, , in particular, don't want override variable's current value.

i looked around online , found suggestion:

try:     some_variable except nameerror:     some_variable = some_expensive_computation() 

i've been using , works fine. however, me has of code that's not paradigmatically correct. code 4 lines, instead of 1 required in lisp, , requires exception handling deal that's not "exceptional."

the context i'm doing interactively development. i'm executing python code file frequently, improve it, , don't want run some_expensive_computation() each time so. arrange run some_expensive_computation() hand every time start new python interpreter, i'd rather automated, particularly code can run non-interactively. how season python programmer achieve this?

i'm using winxp sp3, python 2.7.5 via anaconda 1.6.2 (32-bit), , running inside spyder.

it's bad idea rely on existence or not of variable having meaning. instead, use sentinel value indicate variable not set appropriate value. none common choice kind of sentinel, though may not appropriate if possible output of expensive computation.

so, rather current code, this:

# on in program some_variable = none  # later: if some_variable none:     some_variable = some_expensive_computation()  # use some_variable here 

or, version none significant value:

_sentinel = object() some_variable = _sentinel # means doesn't have meaningful value  # later if some_variable _sentinel:     some_variable = some_expensive_computation() 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -