"once" assigment in Python

Carl Banks pavlovevidence at gmail.com
Fri Sep 14 10:08:17 CEST 2007

On Fri, 14 Sep 2007 06:16:56 +0000, Lorenzo Di Gregorio wrote:

> Hello,
> I've been using Python for some DES simulations because we don't need
> full C speed and it's so much faster for writing models.  During coding
> I find it handy to assign a variable *unless it has been already
> assigned*: I've found that this is often referred to as "once"
> assigment.

I could see reasons for doing something like this at a module level or 
for attributes; such as setting default values when defaults are 
expensive to calculate.  You could, as others have said, initialize the 
variable to a trivial value and then test whether it still held the 
trivial value later, but what's the point?

> The best I could come up with in Python is:
> try:
>   variable
> except NameError:
>   variable = method()
> I wonder if sombody has a solution (trick, whatever ...) which looks
> more compact in coding.  Something like:
> once(variable, method)
> doesn't work, but it would be perfect.

For module level variables you can do something like this:

def once(symbol,method):
    g = globals()
    if symbol not in g:
        g[symbol] = method() 

You'd have to pass a symbol as a string, but that's no big deal.

For local variables you're stuck with trying to catch UnboundLocalError.  
There's a way to do it by examining stack frames, but I don't really 
recommend it: it's inefficient, and the once assignment doesn't make as 
much sense for local variables.

Carl Banks

More information about the Python-list mailing list