Dynamically altering __init__

Kääriäinen Anssi anssi.kaariainen at thl.fi
Thu Oct 13 14:00:39 EDT 2011


Ian Kelly wrote:
"""
You can either pull the function code object out of the module code
object constants:

...
st_code = parser.compilest(st)
func_code = st_code.co_consts[0]
f = types.FunctionType(func_code, {}, '__init__')
...

But you should take care to ensure that the function code object
actually is the first constant.  Or you can just exec your suite and
pull the function from its globals.

src_globals = {}
exec src in src_globals
my_init_func = src_globals['my_init_func']
"""

Thank you very much. I will post a link to a complete example once
I have done the AST transformations etc. I hope this will be useful to
readers of this list. I didn't find such an example, so maybe the next
asker will find it... And when I inevitably do something the wrong
way in my example, I am sure you will correct me :) 

However, this might take some time before ready, I am new to this
stuff. If there is already an example somewhere, that would be really
helpful to me.

Just a quick note, I tested this on Python2.6, and got around 2.3 seconds
per million objects. With an init doing the setattr loop, I got around 4.7
seconds. So the speed difference is there, but as expected, it isn't that
big. Python3 had similar results.

 - Anssi Kääriäinen


More information about the Python-list mailing list