monkey patching __code__
Ned Batchelder
ned at nedbatchelder.com
Fri Mar 18 14:01:31 EDT 2016
On Friday, March 18, 2016 at 10:33:46 AM UTC-4, Sven R. Kunze wrote:
> On 18.03.2016 15:23, Ian Kelly wrote:
> > On Fri, Mar 18, 2016 at 7:47 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> >> Your patched version takes two extra arguments. Did you add the
> >> defaults for those to the function's __defaults__ attribute?
> > And as an afterthought, you'll likely need to replace the function's
> > __globals__ with your own as well.
>
> Thanks again. :-)
>
> Again, why would it make sense for those dunder attributes to be part of
> the function but not of the code object?
Code objects are immutable, and marshal'able (a .pyc file is basically
just a magic-numbered, time-stamped, marshalled code object for the
module). Marshal can't marshal arbitrary Python objects.
Functions are mutable, and constructed at run-time, so can reference
arbitrary Python objects. Since you want default values to possibly
be user-defined Python objects, the defaults are on the function, not
the code object.
--Ned.
More information about the Python-list
mailing list