Editing a function in-memory and in-place

Peter Otten __peter__ at web.de
Thu Apr 27 01:50:18 EDT 2006


Ian Bicking wrote:

> I got a puzzler for y'all.  I want to allow the editing of functions
> in-place.  I won't go into the reason (it's for HTConsole --
> http://blog.ianbicking.org/introducing-htconsole.html), except that I
> really want to edit it all in-process and in-memory.  So I want the
> identity of the function to remain the same, even as I edit the body
> and hopefully the signature too.
> 
> Well, the reason is that I want to edit any function object, without
> having to know who has a reference to the function.  This way editing a
> function or a method or a property.fget can all be done in the same
> way.
> 
> The func_code attributes of functions is writable, but I don't know how
> to create the proper code object.  Just compiling a new body isn't good
> enough.

Can you cheat and just assign another known good func_code object?

>>> def hello(): print "hello"
...
>>> def world(): print "world"
...
>>> def use_it(hello=hello, world=world):
...     hello()
...     world()
...
>>> use_it()
hello
world
>>> world.func_code = hello.func_code
>>> use_it()
hello
hello
>>> hello, world
(<function hello at 0x402904fc>, <function world at 0x40290534>)

Peter




More information about the Python-list mailing list