Skip to content

Instantly share code, notes, and snippets.

@thibaud-opal
Last active November 26, 2022 11:47
Show Gist options
  • Save thibaud-opal/84eceafd67bf67361f5b194aafdd75bc to your computer and use it in GitHub Desktop.
Save thibaud-opal/84eceafd67bf67361f5b194aafdd75bc to your computer and use it in GitHub Desktop.
Using typer with classes as commands
#!/usr/bin/env python3
from my_commands import PrintCommand
from my_lib import PrinterDriver
import os
import typer
app = typer.Typer()
myPrinter = PrinterDriver()
commands = {
"print": PrintCommand(myPrinter)
}
for name, command in commands.items():
app.add_typer(command.load_commands(), name=name)
if __name__ == '__main__':
app()
from my_lib import PrinterDriver
import typer
app = typer.Typer()
class PrintCommand():
def __init__(self, printer: PrinterDriver):
self.__printer = printer
def load_commands(self):
@app.command()
def message(message_body: str):
self.__printer.print(message_body)
@app.command()
def check_ink_levels():
if self.__printer.out_of_ink():
typer.echo("Renew cartridges)
else
typer.echo("Levels OK")
return app
class PrinterDriver():
def print(self, text: str):
typer.echo(text)
def out_of_ink(self)
return self.__inkLevels > 0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment