Created
March 16, 2025 00:13
-
-
Save sockheadrps/f13372f2dbdc57a15defca84c3ff6139 to your computer and use it in GitHub Desktop.
This is an example of a Decorator Factory in python, used in the youtube short: https://www.youtube.com/watch?v=H_0vd0h1_b8&lc=Ugw3j1mHk4fWXCU_0Sp4AaABAg
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
from datetime import datetime | |
def new_event(functions: dict, event: str): | |
def func(callback): | |
def wrapper(self): | |
return callback(self) | |
functions[event] = wrapper | |
return callback | |
return func | |
class StopWatch: | |
def __init__(self): | |
self.start_time = None | |
self.end_time = None | |
self.running = False | |
def start(self): | |
if not self.running: | |
self.start_time = datetime.now() | |
self.running = True | |
return True | |
return False | |
def stop(self): | |
if self.running: | |
self.end_time = datetime.now() | |
self.running = False | |
return True | |
return False | |
def get_time(self): | |
if not self.start_time: | |
return False | |
if self.running: | |
return datetime.now() - self.start_time | |
else: | |
return self.end_time - self.start_time | |
class InputHandler: | |
functions = {} | |
def __init__(self): | |
self.stop_watch = StopWatch() | |
def __call__(self, command: str): | |
if command in self.functions: | |
self.functions[command](self) | |
else: | |
print(f"Unknown command: {command}") | |
@new_event(functions, "start") | |
def start(self): | |
if self.stop_watch.start(): | |
print("Stopwatch started") | |
else: | |
print("Stopwatch already running") | |
@new_event(functions, "stop") | |
def stop(self): | |
if self.stop_watch.stop(): | |
print(f"Elapsed time: {self.stop_watch.get_time()}") | |
else: | |
print("Stopwatch not running") | |
@new_event(functions, "get_time") | |
def get_time(self): | |
if self.stop_watch.get_time(): | |
print(f"Elapsed time: {self.stop_watch.get_time()}") | |
else: | |
print("Stopwatch not running") | |
if __name__ == "__main__": | |
input_handler = InputHandler() | |
while True: | |
command = input("Enter a command: ") | |
input_handler(command) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment