Python context manager cheat sheet

"""
Python context manager cheat sheet

More at https://www.pythonmorsels.com/context-managers/
"""

class Connection:
    def __init__(self, x):
        self.x = x
    def __enter__(self):
        print("Open")
        return self
    def __exit__(self, exception_type, exception, traceback):
        print("Close")


with Connection("Hi") as c:
    print(c.x)

409 views

Share

pym.dev/p/2m46d/

Need to share some Python code?

Create a new snippet