Monkeypatching

metatools.monkeypatch.patch(to_patch, name=None, must_exist=True, max_version=None)[source]

Monkey patching decorator.

Parameters:
  • to_patch – The object to patch.
  • name (str) – The attribute of the object to patch; defaults to name of the patch function.
  • must_exist (bool) – Must the original exist for the patch to be applied?
  • max_version (tuple) – The maximum Python version to apply this patch to.
Returns:

A decorator which takes a function and applies the patch, returning the patched version.

Usage:

# Patch os.listdir to return all lowercase.
@patch(os)
def listdir(original, path):
    return [x.lower() for x in original(path)]

# It is patched in place.    
os.listdir('.')

# The new function still refers to the original.
listdir('.')

# Patch chflags to do nothing in Python up to 2.6.
@patch(os, 'chflags', max_version=(2, 6))
def patched_chflags(func, *args, **kwargs):
    pass
Read the Docs v: latest
Versions
latest
Downloads
PDF
HTML
Epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.