Skip to content

Replace argparse CLI with typer. #606

@pfebrer

Description

@pfebrer

I would like to propose to rewrite sisl CLIs with typer instead of argparse.

Why?

Because:

  1. It autogenerates CLIs for functions using typehints. This has several advantages:
    • We can use sisl functions directly for CLIs, without needing to redefine them and their arguments.
    • To do so, we are forced to type these functions clearly, which is good :)
  2. It looks nice out of the box using rich, which uses colors in the terminal 🎨

Thanks to the first point, I envision we could implement commands like sgeom without all the boilerplate code that there is currently in the Geometry class. In fact, we could automatically create a command for any class that we want in sisl which would include all its methods. E.g.:

sisl density-matrix mulliken ...mulliken options...

Then, all arguments would automatically work without needing to describe the interface separately, as it is done with argparse, which means that it will be much easier to maintain a complex CLI.

What would be needed?

We would need to define a parser for any custom type that might appear in sisl's type hinting if we want to support it. Say for example, if we have a function that receives a geometry:

def does_something(geometry: sisl.Geometry):
     return ...

of course you can't pass a geometry through the CLI. You would then define a parser:

def parse_geometry(geometry: str):
    return sisl.Geometry.read(geometry)

and pass it to typer whenever there is a Geometry annotated function. Typer accepts this kind of parameter options as metadata of Annotated:

def does_something(geometry: typing.Annotated[sisl.Geometry, ...metadata...]):
     return ...

so we would need to define a wrapper that introduces this kind of information before passing it to the typer CLI. But it would work for ALL functions. Another thing that goes into the metadata is the help message of the parameter. It would be retrieved from the docstring. Since all docstrings in sisl follow the same standard, it is quite easy.

I have already implemented the proof of concept wrapper and it works nicely.

I think this would standarize sisl CLIs, making them more familiar to the users, and can facilitate creating new CLIs in the future (e.g. for plotting 😄). If you agree, I could give it a try to reproduce the existing CLIs and create a PR 👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions