Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
patch contextmanager
# file foo.py
def zack():
return "zack
# file patcher.py
class Patch1:
def __init__(self, object, patch):
self.object = object
self.patch = patch
def __enter__(self):
self.pre_patch_value = object
self.object = self.patch
def __exit__(self, exc_type, exc_value, traceback):
self.object = self.pre_patch_value
class Patch2:
def __init__(self, object, name, patch):
self.object = object
self.name = name
self.patch = patch
def __enter__(self):
self.pre_patch_value = getattr(self.object, self.name)
setattr(self.object, self.name, self.patch)
def __exit__(self, exc_type, exc_value, traceback):
setattr(self.object, self.name, self.pre_patch_value)
# file bar.py
import patcher
import foo
with patcher.Patch1(foo.zack, lambda: "bumm"):
print(foo.zack()) # this prints "zack"
with patcher.Patch2(foo, "zack", lambda: "bumm"):
print(foo.zack()) # this print "bumm"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.