ruk·si

🐍 Python
Monkey Patching

Updated at 2018-06-11 01:52

Monkey patching is changing a class runtime. Monkey patching is common in Python. Monkey patching can make applications hard to understand and brittle if used wrong.

import random
from typing import Any, MutableSequence

class Bar:
    _items: MutableSequence

    def __init__(self) -> None:
        self._items = [0, 10, 20]

    def __len__(self) -> int:
        return len(self._items)

    def __getitem__(self, position) -> Any:
        return self._items[position]

b = Bar()
assert b[1] == 10

# b[1] = 5 # this would crash
# random.shuffle(b) # this would crash

def set_item(self: Bar, position: int, item: int):
    self._items[position] = item

Bar.__setitem__ = set_item

# and now they work.
b: MutableSequence
b[1] = 5
random.shuffle(b)

Source

  • Fluent Python, Luciano Ramalho