Last active
October 7, 2023 17:07
-
-
Save arjunprakash027/b75b0b5e55601c68b65e5f7d09ad1b0d to your computer and use it in GitHub Desktop.
A short python code to understand the use of context managers in python (with statement)
This file contains hidden or 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
#below is the class based context manager | |
class ContextTest: | |
def __init__(self) -> None: | |
print("initialized the ContextManager") | |
def __enter__(self) -> None: | |
print("entered into the with block") | |
def __exit__(self,exc_type,exc_value,exc_traceback) -> None: | |
print(exc_type,exc_value,exc_traceback) | |
print("excited the with block") | |
with ContextTest() as manager: | |
print("inside the with") | |
#decorator based context manager | |
from contextlib import contextmanager | |
@contextmanager | |
def write_something(name): | |
try: | |
print("entered the with block") | |
yield name | |
finally: | |
print("exited the with block") | |
with write_something("hello") as name: | |
print("inside the with block:",name) | |
#a bullet point manager (a fun implementation of with statement) | |
class BulletList: | |
def __init__(self)->None: | |
self.intend = 0 | |
def __enter__(self): | |
self.intend += 1 | |
return self | |
def __exit__(self,exc_type,exc_value,exc_traceback) -> None: | |
self.intend -= 1 | |
def bulletType(self) -> str: | |
types = ["o ","- ","* "] | |
return types[self.intend%3] | |
def item(self,text)-> None: | |
print(" "*self.intend + self.bulletType() + text) | |
with BulletList() as bullet: | |
bullet.item("hello") | |
with bullet: | |
bullet.item("world") | |
bullet.item("python") | |
with bullet: | |
bullet.item("is awesome") | |
with bullet: | |
bullet.item("and so is you") | |
bullet.item("and so is me") | |
bullet.item("and so is we all") | |
with bullet: | |
bullet.item("and so is you and me") | |
bullet.item("and so is me and all") | |
bullet.item("and so is we all and us") | |
class TesingWith: | |
def __init__(self) -> None: | |
self.num = 0 | |
def __enter__(self): | |
self.num += 1 | |
return self | |
def __exit__(self,exc_type,exc_value,exc_traceback) -> None: | |
self.num -= 1 | |
def display(self) -> None: | |
print(self.num) | |
with TesingWith() as t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
with t: | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() | |
t.display() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment