Can you monkey patch methods on core types in Python? Can you monkey patch methods on core types in Python? python python

Can you monkey patch methods on core types in Python?


No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. (Multiple interpreters in the same process are possible through the C API, and there has been some effort towards making them usable at Python level.)

However, classes defined in Python code may be monkeypatched because they are local to that interpreter.


What exactly do you mean by Monkey Patch here? There are several slightly different definitions.

If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:

class Foo:  pass # dummy classFoo.bar = lambda self: 42x = Foo()print x.bar()

If you mean, "can you change a class's methods at runtime and make all of the instances of that class change after-the-fact?" then the answer is yes as well. Just change the order slightly:

class Foo:  pass # dummy classx = Foo()Foo.bar = lambda self: 42print x.bar()

But you can't do this for certain built-in classes, like int or float. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.

I'm not really clear on why you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!


def should_equal_def(self, value):    if self != value:        raise ValueError, "%r should equal %r" % (self, value)class MyPatchedInt(int):    should_equal=should_equal_defclass MyPatchedStr(str):    should_equal=should_equal_defimport __builtin____builtin__.str = MyPatchedStr__builtin__.int = MyPatchedIntint(1).should_equal(1)str("44").should_equal("44")

Have fun ;)