Created
February 27, 2022 21:04
-
-
Save thomasms/a6c6240aa7754c16ce088d2c83cbbb38 to your computer and use it in GitHub Desktop.
Using exceptions in python to transport values without explicit dependencies
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
# define in some util somewhere | |
class MyException(Exception): | |
class A: | |
value = 4 | |
# raise an exception with a custom value to be caught elsewhere | |
def myfunc(b): | |
a = MyException | |
a.value = b | |
raise a | |
# catch the exception and get the value in another part of the code | |
try: | |
myfunc(6) | |
except MyException as e: | |
print(f"Got {e.__class__.__name__} with value: {e.value}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment