jmhobbs

Hot Patching Python Objects

Hot patching is a touchy issue, it's often frowned upon, and rightly so. But sometimes it's the easiest way to get what you want.

Usually in Python you would patch a class with a new method, which works fine. But what if you only wanted to patch a single instance of that class, and not all of them?

Turns out that's pretty easy with the types library.

To use it you define your patch method as a regular function, then you call types.MethodType to properly bind it, and you are done!

Here is a simple example:

#!/usr/bin/env python

import types

class Chicken(object):
    def cluck(self):
        return "cluck, cluck"

chicken = Chicken()

# Prints, "cluck, cluck"
print chicken.cluck()

duck = Chicken()

# Define our patch method
def quack(self):
    return "quack! quack!"

# Bind it properly to the duck instance
duck.quack = types.MethodType(quack, duck)

# Prints "quack! quack!"
print duck.quack()

# Bind it again, overriding the cluck method
duck.cluck = types.MethodType(quack, duck)

# Prints "quack! quack!"
print duck.cluck()

# Prints "cluck, cluck"
print chicken.cluck()

# Now override cluck at the class level
Chicken.cluck = quack

# Prints "quack! quack!"
print chicken.cluck()

Easy!