Python-version-sensitive monkeypatching.
Project description
- Contact:
- z@etiol.net
ook is a simple library to assist with monkeypatching Python methods and functions on a per-Python-version basis. It provides one decorator, patch, which conditionally patches callables depending on which version of Python is running.
Example
This one’s used in ook’s test suite:
import itertools from ook import patch @patch(itertools, 2.5) def combinations(iterable, r): # From <http://docs.python.org/release/2.6/library/itertools.html>. pool = tuple(iterable) n = len(pool) if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
Usage
patch accepts an arbitrary number of version arguments, in a variety of formats:
@patch(some.module.or.class, 2.5, "2.6.8", (2, 7, 3), 3) def method_or_function(signature): """Do something.""" pass
… as well as min and max keyword arguments:
@patch(some.module.or.class, min="2.5.4", max=2.7) def method_or_function(signature): """Do something.""" pass
… which can be combined:
@patch(some.module.or.class, "3.1.5", max=3.1) def method_or_function(signature): """Do something.""" pass
Note: If you specify both keyword and non-keyword version arguments, the patch will only take effect if both the explicitly specified versions and the implied version ranges are satisfied.
With no arguments other than the module or class to be patched, patch applies the patch regardless of Python version:
@patch(some.module.or.class) def method_or_function(signature): """Do something, no matter what.""" pass
Installation
This should do the trick:
pip install ook
Credits / Copyright
ook was (cough) “inspired” by Guido van Rossum’s monkeypatch recipe. Thanks, Guido :-)
It’s released under the GNU General Public License (version 3 or later), a copy of which is included with this distribution in the file COPYING.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.