monkey patching __code__

Matt Wheeler m at funkyhat.org
Fri Mar 18 19:58:29 EDT 2016


On 18 March 2016 at 11:49, Sven R. Kunze <srkunze at mail.de> wrote:
> Hi,
>
> we got an interesting problem. We need to monkeypatch Django's reverse
> function:
>
>
> First approach:
>
> urlresolvers.reverse = patched_reverse
>
>
> Problem: some of Django's internal modules import urlresolvers.reverse
> before we can patch it for some reasons.
>
>
> Second approach:
>
> urlresolvers.reverse.__code__ = patched_reverse.__code__
>
>
> Unfortunately, we got this error:
>
>>>> reverse('login')
>
> patched_reverse() takes at least 3 arguments (1 given)
>
>
> These are the functions' signatures:
>
> def patched_reverse(viewname, urlconf=None, args=None, kwargs=None,
> prefix=None, current_app=None, get=None, fragment=None):
> def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None,
> current_app=None):
>
>
> Some ideas?

I know you have a working solution now with updating the code &
defaults of the function, but what about just injecting your function
into the modules that had already imported it after the
monkeypatching?

Seems perhaps cleaner, unless you'd end up having to do it to lots of modules...

-- 
Matt Wheeler
http://funkyh.at



More information about the Python-list mailing list