Functions and code objects
Fuzzyman
fuzzyman at gmail.com
Thu Jul 27 11:01:23 EDT 2006
Simon Forman wrote:
> Fuzzyman wrote:
[snip..]
> > I was hoping I could get to the code object for the *body* of the
> > function. Looks like that won't be possible without dis-assembling the
> > bytecode or other tricks even more hackish than what I've already done.
> >
> > For the record, the code I was using was :
> >
> > x = 3
> > def f(x):
> > print x
> >
> > CodeType = type(f.func_code)
> >
> > def convert_function(f):
> > code = f.func_code
> > nlocals = max(code.co_nlocals - code.co_argcount, 0)
> > newCode = CodeType(0, nlocals, code.co_stacksize, code.co_flags,
> > code.co_code, code.co_consts, code.co_names,
> > code.co_varnames, code.co_filename,
> > code.co_name,
> > code.co_firstlineno, code.co_lnotab,
> > code.co_freevars,
> > code.co_cellvars)
> > return newCode
> >
> > print convert_function(f)
> > exec convert_function(f)
> >
> > Fuzzyman
> > http://www.voidspace.org.uk/python/index.shtml
>
> Out of curiosity, why are you doing this?
>
In Ruby anonymous code blocks (which take parameters and can presumably
return values) are executed within the scope in which they are used,
rather than the scope that they are defined.
I wanted to see how close to that I could get in Python. Obviously code
could be compiled from a string, but I thought extracting it from the
body of a function was closer.
All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
> Peace,
> ~Simon
More information about the Python-list
mailing list