monkey patching __code__

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 18 09:47:28 EDT 2016


On Fri, Mar 18, 2016 at 5:49 AM, 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?

Your patched version takes two extra arguments. Did you add the
defaults for those to the function's __defaults__ attribute?

This sounds like a pretty hairy thing that you're trying to do. Surely
there must be some better way to accomplish the same goal.



More information about the Python-list mailing list