Skip to content

Instantly share code, notes, and snippets.

@markshannon
Last active February 17, 2023 14:11
Show Gist options
  • Save markshannon/536322adb5cb7b0dc765d036b0e9ab02 to your computer and use it in GitHub Desktop.
Save markshannon/536322adb5cb7b0dc765d036b0e9ab02 to your computer and use it in GitHub Desktop.
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
@iritkatriel
Copy link

What is MyLeave?

@markshannon
Copy link
Author

Typo. Let me fix that.

@markshannon
Copy link
Author

markshannon commented Feb 15, 2023

It should be the context manager class.

@iritkatriel
Copy link

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