pythonpython-3.xpython-clicktyper

Changing command order in Python's Typer


I want Typer to display my commands in the order I have initialized them and it displays those commands in alphabetic order. I have tried different approaches including this one: https://github.com/tiangolo/typer/issues/246 In this I get AssertionError. Others like subclassing some Typer and click classes does actually nothing.

I want the commands to be in the same order as in this working piece of code:

import typer
import os

app = typer.Typer()


@app.command()
def change_value(file_name, field):
    print("Here I will change the", file_name, field)


@app.command()
def close_field(file_name, field):
    print("I will close field")


@app.command()
def add_transaction(file_name):
    print("I will add the transaction")


if __name__ == "__main__":
    app()

Please help :)


Solution

  • All right I have found solution elsewhere, while trying to post the ticket to Typer (they have a really comprehensive troubleshooting!)

    https://github.com/tiangolo/typer/issues/428

    The app that displays commands in the order I want them displayed looks like this:

    import typer
    from click import Context
    from typer.core import TyperGroup
    
    class OrderCommands(TyperGroup):
      def list_commands(self, ctx: Context):
        return list(self.commands)
    
    app = typer.Typer(
        cls=OrderCommands,
        no_args_is_help=True
    )
    
    
    @app.command()
    def change_value(file_name, field):
        print("Here I will change the", file_name, field)
    
    
    @app.command()
    def close_field(file_name, field):
        print("I will close field")
    
    
    @app.command()
    def add_transaction(file_name):
        print("I will add the transaction")
    
    
    if __name__ == "__main__":
        app()