monkey patching __code__

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 18 11:26:45 EDT 2016


On Fri, Mar 18, 2016 at 9:01 AM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 18.03.2016 15:48, Ian Kelly wrote:
>>
>> Well I didn't design it, so I'm not really sure. But it could be argued
>> that the defaults are intrinsic to the function declaration, not the code
>> object, as not all code objects even have arguments. It also makes it
>> straight-forward to create a new function that uses the same code but with
>> different defaults or globals.
>
>
> It occurred to me after I sent that email.
>
> However, changing globals is not possible.

Well it may not work for your case, but in general you can do:

from types import FunctionType

new_function = FunctionType(old_function.__code__, new_globals, ...)



More information about the Python-list mailing list