Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to override a method defined in a module of a third party library

I've installed a third party library tornado by pip and need to override a method, say to_unicode defined in the global scope of a module say tornado.escape. So that all calls to that method will use my overridden version. Or maybe, I would want to control it so that only my code will use the overridden version.

If it had been defined inside a class, I'd have no problem to subclass it and override the method! But since this is just a method, I'm wondering how to override it.

Surprisingly, I found not suitable solution in SO, is this kind of impossible to achieve?

like image 751
Shafiul Avatar asked May 14 '14 06:05

Shafiul


People also ask

How do you overwrite a method in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

How do you override a private method in Python?

You can do it still, by naming your object just so: def _Foo__method(self): where you prefix the method name with one more underscore and the defining classname (so in this case prefixed with _Foo ). The process of renaming methods and attributes with a double underscore is called private name mangling.

Can you override built in functions in Python?

Python has a number of built-in functions that are always accessible in the interpreter. Unless you have a special reason, you should neither overwrite these functions nor assign a value to a variable that has the same name as a built-in function.

What is __ module __?

The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.


1 Answers

You can simply rebind the name of an object (in this case, a module-level function) to a different object. For example, if you want to have math.cos work with degrees instead of radians, you could do

>>> 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

However, that might cause problems to other functions that use that module...

like image 111
Tim Pietzcker Avatar answered Oct 01 '22 03:10

Tim Pietzcker