Last active
September 15, 2021 03:08
-
-
Save spinfish/766fdcfd45316eb8e1a0ea39eb35345b to your computer and use it in GitHub Desktop.
This was a stupid idea, and is going to be useless with the new match case PEP lol
This file contains 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
class Switch: | |
"""A shitty equivalent of the `switch` statement.""" | |
__slots__ = ("__dictionary", "__otherwise") | |
def __init__(self, dictionary, *, otherwise=None): | |
if not all(callable(value) for value in dictionary.values()): | |
raise TypeError("all values of the dictionary must be callables") | |
self.__dictionary = dictionary | |
self.__otherwise = otherwise or (lambda: None) | |
def __call__(self, value): | |
try: | |
result = self.__dictionary[value]() | |
except KeyError: | |
result = self.__otherwise() | |
finally: | |
return result | |
def print_aaaa(): | |
print("AAA") | |
def print_else(): | |
print("else lol") | |
def main(user_input): | |
switch = Switch({"a": print_aaaa}, otherwise=print_else) | |
switch(user_input.lower()) | |
if __name__ == '__main__': | |
main("A") | |
main("b") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment