[Python-ideas] use "as" for block scope support

Steven D'Aprano steve at pearwood.info
Tue Jul 26 01:10:14 CEST 2011


海韵 wrote:
> 1.
> but what about ( t * s + t / s )? temp var always keep in memory.
> (should not reduce ( t + s ) to ( 2 * x ) since x, y may not a number.
> any operator here should be conside as  independent function. )

What about it? The temporary variables will go out of scope when the 
function exists, and be garbage collected, the same as every other local 
variable.


> 2. you got an extra lambda, that means:
> In runtime:
> lambda = MAKE_FUNCTION/MAKE_CLOSURE =  PyFunction_New
> lambda call = CALL_FUNCTION =  PyFrame_New +  PyEval_EvalFrameEx
> all of them are heavy, (you can check the source code)
> but:
> as = PyCell_New
> as enter = SETUP_FINALLY = PyFrame_BlockSetup
> as leave = END_FINALLY = PyFrame_BlockPop
> which is much much much more more more cheaper than above.

Sounds like premature optimization to me. I would like to see actual, 
real-world code where the performance bottleneck is setting up functions.


> 3.
> try convert this to the lambda form as mention:
> R= lambda x, y: (x+y as t, x-y as s)(t * s as u, t/s as v)(u << v as
> p, u>>v as q) p ** q

I wouldn't even *try* to convert that to a lambda. That is ugly, 
unmaintainable code. To understand it, I had to first write it out in 
block form:

def R(x, y):
     with x+y as t, x-y as s:
         with t*s as u, t/s as v:
             with u << v as p, u >> v as q
                 return p**q


which is much simpler to read and maintain when written like this:

def R(x, y):
     t, s = x+y, x-y
     u, v = t*s, t/s
     p, q = u << v, u >> v
     return p**q


I consider this proposal to encourage excess and unnecessary 
encapsulation of variables. Not every expression needs to be it's own block.


-- 
Steven



More information about the Python-ideas mailing list