Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top