tut14
This commit is contained in:
36
Tutorium/tut14/src/commands.py
Normal file
36
Tutorium/tut14/src/commands.py
Normal file
@ -0,0 +1,36 @@
|
||||
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))
|
||||
|
Reference in New Issue
Block a user