Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
patch contextmanager
# file
def zack():
return "zack
# file
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 = name
self.patch = patch
def __enter__(self):
self.pre_patch_value = getattr(self.object,
setattr(self.object,, self.patch)
def __exit__(self, exc_type, exc_value, traceback):
setattr(self.object,, self.pre_patch_value)
# file
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.