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

I installed the third-party tornado pip library and must override the method , say to_unicode, defined in the global scope of the module tornado.escape. So that all calls to this method use my overridden version. Or maybe I would like to control this so that only my code uses an overridden version.

If it were defined inside the class, I would have no problem subclassing it and overriding the method! But since this is just a method, I wonder how to redefine it.

Surprisingly, I did not find a suitable solution in SO, is this impossible to achieve?

+4
source share
1 answer

You can simply rewrite the name of the object (in this case, the module level function) to another object. For example, if you want to math.coswork 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, this can cause problems with other functions that use this module ...

+7
source

Source: https://habr.com/ru/post/1540466/


All Articles