Frame hacking

George Sakkis george.sakkis at gmail.com
Wed Dec 13 10:03:13 EST 2006


George Sakkis wrote:
> Gabriel Genellina wrote:
> > On 12 dic, 17:46, "George Sakkis" <george.sak... at gmail.com> wrote:
> >
> > > I wonder if the following is possible:
> > >
> > > def inject_n_call(func, **kwds):
> > >     '''Call func by first updating its locals with kwds.'''
> > >
> > > def f():
> > >     return x*y
> > >
> >
> > >>> eval(f.func_code, dict(x=3,y=4))
> > 12
>
> Sweet! I think I just reinvented what eval does in this case by
> fiddling with sys.settrace and frame.f_globals. Glad to trash my
> 20-line function for an one-liner :)

Actually I thought about this and it would be more convenient in my
case if I could change the "signature" of f to "def f(x,y)" so that I
can pass positional arguments instead of a keywords (don't ask why).
I've tried creating a new code object by tweaking co_varnames,
co_argcount, co_nlocals and making a new function out of it but it
doesn't work.. does co_code have to be changed as well, and if so, how?

George




More information about the Python-list mailing list