fastapi / typer

Typer, build great CLIs. Easy to code. Based on Python type hints.
https://typer.tiangolo.com/
MIT License
15.93k stars 675 forks source link

[QUESTION] #271

Open mr-wook opened 3 years ago

mr-wook commented 3 years ago

Description

How do you pass instance methods to process commands from typer, it appears to choke on ?

sathoune commented 3 years ago

Could you provide some minimal example?

mr-wook commented 3 years ago

!/bin/env python3

if True: import typer

if name == "main": typer = typer.Typer()

class App():
    def __init__(self):
        global typer
        self._typer = typer
        self._x = self._y = self._z = 0.0

    def __str__(self):
        ostr = f"({self._x:.2f}, {self._y:.2f}, {self._z:.2f})"
        return ostr

    @typer.command()
    def x(self, x: float):
        self._x = x
        self._typer.echo(self)

    @typer.command()
    def y(self, y: float):
        self._y = y
        self._typer.echo(self)

    @typer.command()
    def z(self, z: float):
        self._z = z
        self._typer.echo(self)

    def run(self):
        self._typer()

app = App()
app.run()

envy-m7[162]% ~/src/python/test_typer.py x --help Usage: test_typer.py x [OPTIONS] SELF X

Arguments: SELF [required] X [required]

Options: --help Show this message and exit.

sathoune commented 3 years ago

I created a repo that has some examples where typer is ussed inside classes: https://github.com/captainCapitalism/typer-oo-example . It was an answer to Issue #261

In short using decorator will give you these errors, but using typer.command as function call: typer.command()(self.some_method) works fine. I don't understand yet what is the deal withself` showing up here and not in my examples but I will explore and should come back in the following days.

mr-wook commented 3 years ago

Muchas Gracias, Extremely Helpful, Thanks again!

oramirite commented 2 years ago

@captainCapitalism Wonderful little repo you set up here that's coming in extremely handy for me. I was mostly just using it as a reference, but with a recent revision I may end up mirroring your setup almost exactly.

Did you ever figure out the exact issue with the decorators? I wanted to use them in a class-based setup to avoid manually registering the commands in init if possible. Would be slightly cleaner.