Skip to content

Instantly share code, notes, and snippets.

@spinfish
Last active September 15, 2021 03:12
Show Gist options
  • Save spinfish/f8398785ddbe30be7b9be8855f38ca4c to your computer and use it in GitHub Desktop.
Save spinfish/f8398785ddbe30be7b9be8855f38ca4c to your computer and use it in GitHub Desktop.
A context manager class that can uwuify text.
from uwuify import uwu
class UwUifer:
"""
Extremely simple example of a context manager class which has
the dunder enter and __exit__ methods implemented, as well as
a ``do_uwu`` method to uwuify text.
"""
def close(self):
print("Goodbye.")
def do_uwu(self, text):
"""UwUifies the given text and returns it in a formatted string."""
return "Enjoy your uwuified text: {}".format(uwu(text))
# This method will be called before the statement body is executed (i.e., as we
# *enter* the `with` block).
#
# This method should return an object that is bound to the variable after `as`.
# For example, `with Ctx() as h: ...`, should return `h` (instance of `Ctx`).
#
# By default it is None, and is optional. A common pattern is to return self,
# the instance itself.
def __enter__(self):
return self
# This method will be called when the body of the `with` block has finished executing.
# This will be called even if an exception occurs.
# If it is not exited due to an exception, `exc_type`/`exc_val`/`exc_tb` will all be `None`.
def __exit__(self, typ, value, traceback):
self.close()
# If you want any errors that occur within the `with` block to be suppressed,
# have a `return True` here instead.
#
# The reason we have a False being returned here is because if an error *does*
# occur within our `with` block, the error will be raised and you can handle it.
#
# you could also return nothing, which then returns None which evaluates to False
# but it is better to return it explicitly
return False
# Take these examples (`uncaught` and `caught`) and pay close attention to what happens
# at the end of each `with` block within each function.
def uncaught():
"""Does not handle the KeyError."""
with UwUifer() as uwu:
print(uwu.do_uwu("Hello World!"))
md = {"hi": "there"}
# Here the `with` block will terminate and a KeyError will be raised
uwu.do_uwu(md["goodbye"])
# Because a KeyError has been raised, Python won't see this
print("After the with block...")
def caught():
"""Actually handles the KeyError."""
with UwUifer() as uwu:
print(uwu.do_uwu("Hello world!"))
md = {"hi": "there"}
try:
print(uwu.do_uwu(md["goodbye"]))
except Exception as e:
print("{0.__class__.__name__}: {0}".format(e))
print("After the with block...")
# Now try calling uncaught and then caught and see what happens!
from uwuify import uwu
class UwUifer:
"""
Extremely simple example of a context manager class which has
the dunder enter and __exit__ methods implemented, as well as
a ``do_uwu`` method to uwuify text.
"""
def close(self):
print("Goodbye.")
def do_uwu(self, text):
"""UwUifies the given text and returns it in a formatted string."""
return "Enjoy your uwuified text: {}".format(uwu(text))
def __enter__(self):
return self
def __exit__(self, typ, value, traceback):
self.close()
return False
def uncaught():
"""Does not handle the KeyError."""
with UwUifer() as uwu:
print(uwu.do_uwu("Hello World!"))
md = {"hi": "there"}
uwu.do_uwu(md["goodbye"])
print("After the with block...")
def caught():
"""Actually handles the KeyError."""
with UwUifer() as uwu:
print(uwu.do_uwu("Hello world!"))
md = {"hi": "there"}
try:
print(uwu.do_uwu(md["goodbye"]))
except Exception as e:
print("{0.__class__.__name__}: {0}".format(e))
print("After the with block...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment