Last active
February 17, 2023 14:11
-
-
Save markshannon/536322adb5cb7b0dc765d036b0e9ab02 to your computer and use it in GitHub Desktop.
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
class CallsLeave: | |
def __init__(self, cls, obj): | |
self.cls = cls | |
self.obj = obj | |
def __call__(self, exc, val, tb): | |
self.cls.__leave__(self.obj, val) | |
class CallsLeaveDescriptor: | |
def __init__(self, cls): | |
self.cls = cls | |
def __get__(self, obj, objtype=None): | |
return CallsLeave(self.cls, obj) | |
class ContextManagerUsingLeave: | |
def __enter__(self): | |
print("enter") | |
return self | |
def __leave__(self, exc): | |
print("__leave__", self, exc) | |
# Patch in __exit__ | |
ContextManagerUsingLeave.__exit__ = CallsLeaveDescriptor(ContextManagerUsingLeave) | |
with ContextManagerUsingLeave(): | |
pass |
It's not so simple.
def __get__(self, obj, objtype=None):
return CallsLeave(self.cls, obj)
When we invoke this on a class and obj is None we need to do something else.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It should be the context manager class.