[Python-Dev] once [was: Simple Switch statementZ]

Ron Adam rrr at ronadam.com
Wed Jun 28 23:24:22 CEST 2006


> I believe at least one poster has pointed out that 'once' (if defined
> suitably) could be used as a better way to do this:
> 
>   def index_functions(n):
>     return [(lambda: once i) for i in range(n)]
> 
> But delaying the evaluation of the once argument until the function is
> called would break this, since none of these functions are called
> until after the loop is over, so the original bug would be back.


I've been trying to sort out the different terms once, const, and 
static.  Below is what feels right to me.  Not that it is right, but how 
I think I would interpret them as if I were new to python and what would 
be easiest to understand.

The "once" below isn't what is being discussed but it seems to me what 
the word implies.


once = Evaluate an expression once and use that value in place of the 
expression if the same line is executed again.

     for n in range(10):
        print n                    # print 0 through 9

     for n in range(10):
        print (once n)             # prints 0 ten times

    a = (once 3 * pi)              # replaces 3 * pi with value

    b = i + (once sum(range(10)))  # evaluate 'sum()' only once
                                   # use the result many times
                                   # in a loop


const = Bind a name to a value and protect it from further change in the 
current scope at execution time.  This protects the name, but not the 
object.  A constant mutable is still mutable.  The name just can't be 
rebound to another object.

    def foo(i):
       i += 1        # this is ok
       const i       # it becomes locked at this point
       i = 2         # this gives an exception


static = Evaluate an expression at function compile time.  Any values in 
the expression need to be known at function compile time.  They can be 
static names in the current scope previously evaluated.

    a, b = 1, 2
    def foo(i):
       static j = a+b
       static k = j*2

       k = 25           # ok if not also const
       const j          # protect it from further change
       j = 12           # give an exception


The term static does seem to suggest lack of change, so it could also 
have the const property by default.  If it were allowed to be changed, 
then would it keep the changed value on the next call?  Probably not a 
good idea for the use cases being discussed.


So given the above only the static version solves the above lambda loop 
and returns a list of functions that return values 0 through n.

I think all three of these properties are useful, but I don't think we 
need all three of them.


Cheers,
    Ron

(* I'll be away from my computer for about a week after Tomorrow morning.)




More information about the Python-Dev mailing list