Files
eidp-2023/Tutorium/tut14/src/commands.py
2024-02-02 09:03:35 +01:00

36 lines
971 B
Python

from typing import Callable, Iterator
class CommandExecutor[R]:
def __init__(self):
self.__commands: dict[str, Callable[..., R]] = {}
def run(self, name: str, *args, **kwargs) -> list[R]:
results : list[R] = []
for command_name, command in self.__commands.items():
if command_name == name:
results += [command(*args, **kwargs)]
return results
def register(self, cmd: Callable[..., R]) -> Callable[..., R]:
self.__commands[cmd.__name__] = cmd
return cmd
if __name__ == '__main__':
app = CommandExecutor[str]()
@app.register
def hello_world() -> str:
return 'hello_world'
@app.register
def divide(a: int, b: int) -> str:
if b == 0:
return "tried to divide by zero"
return str(a / b)
print(app.run('hello_world'))
print(app.run('divide', 5, 0))
print(app.run('divide', 10, 2))