Last active
September 24, 2019 09:29
-
-
Save xsteadfastx/f8d076b709e45a4c9de58d5df335d231 to your computer and use it in GitHub Desktop.
patch contextmanager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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