optimization
Duncan Booth
duncan.booth at invalid.invalid
Tue Dec 2 07:52:55 EST 2008
Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> Which makes me wonder, is there anything we can do with that code object
> from Python code? I can disassemble it:
>
>>>> import dis
>>>> dis.dis(outer.func_code.co_consts[1])
> 3 0 LOAD_CONST 0 (None)
> 3 RETURN_VALUE
>
> Anything else?
Provided it doesn't take any arguments you can run the code with exec or
eval:
>>> def outer():
def inner():
print "inner called"
return inner()
>>> eval(outer.func_code.co_consts[1])
inner called
More usefully you could use the code object to construct another function,
e.g. if you wanted to change the values of some default arguments.
>>> types.FunctionType(outer.func_code.co_consts[1], globals())()
inner called
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list