17

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?

Shafiul
  • 2,832
  • 9
  • 37
  • 55
  • you probably should define a class that heritates from tornado and there redefine your wanted method so it will be called instead of the parent's one – daouzli May 14 '14 at 06:12
  • Like I mentioned, the method I want to override is NOT defined inside any class, rather defined in the module's global scope! So how I'm going to override if there's no class in the first place? – Shafiul May 14 '14 at 06:20

1 Answers1

21

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

Community
  • 1
  • 1
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561