I am attempting to take the source code of a function, add code to it, and then put it back in the original function.
Basically like so:
new_code = change_code(original_code)
throwaway_module = ModuleType('m')
exec(new_code, throwaway_module.__dict__)
func.__code__ = getattr(throwaway_module, func.__name__).__code__
This works perfectly when new_code
doesn't contain any name which wasn't in the original function.
However when new_code
contains a variable name which wasn't there in the original func
, then on the last line I get the following error:
ValueError: func() requires a code object with 1 free vars, not 0
Any ideas?
EDIT:
It seems I have found where in the CPython source code this exception is raised (file funcobject.c). Omitted some lines for clarity:
static int
func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
{
Py_ssize_t nfree, nclosure;
// ... lines omitted
nfree = PyCode_GetNumFree((PyCodeObject *)value);
nclosure = (op->func_closure == NULL ? 0 :
PyTuple_GET_SIZE(op->func_closure));
if (nclosure != nfree) {
PyErr_Format(PyExc_ValueError,
"%U() requires a code object with %zd free vars,"
" not %zd",
op->func_name,
nclosure, nfree);
return -1;
}
Py_INCREF(value);
Py_XSETREF(op->func_code, value);
return 0;
}
Does this help you help me? :)