Rationale for read-only property of co_code

Peter Otten __peter__ at web.de
Thu Apr 3 06:28:56 EDT 2008


João Neves wrote:

> Let me give a very basic example. Say we have these two functions:

I suppose you mean

>>> def inc(x): return x + 1
...
>>> def dec(x): return x - 1
...
>>> inc(1), dec(1)
(2, 0)


> Examining the compiled bytecodes for these two functions:
> 
> >>> inc.func_code.co_code
> '|\x00\x00d\x01\x00\x17}\x00\x00d\x00\x00S'
> 
> >>> dec.func_code.co_code
> '|\x00\x00d\x01\x00\x18}\x00\x00d\x00\x00S'
> 
> Now suppose that I wanted to mess with inc, and have it behave like
> dec.

>>> inc.func_code = dec.func_code
>>> inc(1), dec(1)
(0, 0)

There you are, and there wasn't even a slight chance that you combined the
byte code with an incompatible function signature ;)

Peter



More information about the Python-list mailing list