0

I've installed a package in my Django project, let's say pip install somepackage

This package comes with some modified views, so I do:

class MyView(somepackage.CustomView):
    ...

But there's some method in somepackage.utils (somepackage.utils.somemethod) that I need to customize. If this were a method in somepackage.CustomView I could do:

class MyView(somepackage.CustomView):

    def somemethod(...):
        ...

But it's not.

How can I override that util's method?

Gocht
  • 9,924
  • 3
  • 42
  • 81
  • You want to replace _that_ method with your own? It's not a method, it's function in `sompackage.utils` module. – Michał Fita Nov 25 '15 at 22:12
  • You can do monkey patch. https://web.archive.org/web/20120730014107/http://wiki.zope.org/zope2/MonkeyPatch – Shang Wang Nov 25 '15 at 22:13
  • @MichałF Yes, I found something there that I need to replace, I could write a new code for that method without breaking anything else, but I don't know how – Gocht Nov 25 '15 at 22:13
  • @ShangWang What does 'monkey patch' means? Sorry but I don't know. – Gocht Nov 25 '15 at 22:14
  • http://stackoverflow.com/questions/5626193/what-is-a-monkey-patch – Shang Wang Nov 25 '15 at 22:14
  • @ShangWang That look like something made by a monkey, but I need to pass one param to this method, I think this is for callable method without params, right? – Gocht Nov 25 '15 at 22:16
  • I'm giving this straight from head: `somepackage.utils.__old_somemethod = somepackage.utils,_old_somemethod` then you need to write your function and assign it for `somepackage.utils.somemethod`. This should work if your `somepackage` is written in pure Python. If the `__old_somemethod` don't work straightway, you may need to amend module's __dict__ first. Google is your friend if you now what you're looking for. – Michał Fita Nov 25 '15 at 22:17
  • There's also this one that should meet what you need: http://stackoverflow.com/questions/23646826/python-how-to-override-a-method-defined-in-a-module-of-a-third-party-library – Shang Wang Nov 25 '15 at 22:18
  • @ShangWang a monkey patch worked, thanks, consider give it as an answer, I will accept it. – Gocht Nov 25 '15 at 22:27

1 Answers1

0

As the discussion goes, I think we can do "monkey patch" on the module level functions, which basically replaces the function with your version. There's already an answer that explains this, but quote it here (replace math with somepackage.utils):

>>> import math
>>> math.cos(90)
-0.4480736161291701
>>> old_cos = math.cos
>>> def new_cos(degrees):
...     return old_cos(math.radians(degrees))
...
>>> math.cos = new_cos
>>> math.cos(90)
6.123233995736766e-17
Community
  • 1
  • 1
Shang Wang
  • 24,909
  • 20
  • 73
  • 94