lambdas vs functions: a bytecode question
Fredrik Lundh
fredrik at pythonware.com
Sat Dec 18 02:30:06 EST 2004
Fernando Perez wrote:
> there are a couple of threads on lambdas today, which got me curious about
> their differences as far as bytecode goes:
>
> planck[~]|2> lf=lambda x: x**2
> planck[~]|3> def ff(x): return x**2
> |.>
> planck[~]|4> import dis
> planck[~]|5> dis.dis(lf)
> 1 0 LOAD_FAST 0 (x)
> 3 LOAD_CONST 1 (2)
> 6 BINARY_POWER
> 7 RETURN_VALUE
> planck[~]|6> dis.dis(ff)
> 1 0 LOAD_FAST 0 (x)
> 3 LOAD_CONST 1 (2)
> 6 BINARY_POWER
> 7 RETURN_VALUE
> 8 LOAD_CONST 0 (None)
> 11 RETURN_VALUE
>
> Can someone explain to me what the extra two bytecodes at the end of the
> function version (ff) are for?
looks like a buglet in Python 2.3 (and probably in earlier versions). the code
generator seems to think that it has to be *really* sure that the function cannot
return without returning None.
Python 2.4 doesn't have this "feature":
>>> import dis
>>> f = lambda x: x**2
>>> def g(x): return x**2
...
>>> dis.dis(f)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_POWER
7 RETURN_VALUE
>>> dis.dis(g)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_POWER
7 RETURN_VALUE
</F>
More information about the Python-list
mailing list