Textualize / trogon

Easily turn your Click CLI into a powerful terminal application
MIT License
2.4k stars 54 forks source link

trogon tui fallback #48

Closed cariaso closed 1 year ago

cariaso commented 1 year ago

I'd like to use trogon when it's available, and fail gracefully when it is not. It seems this should be sufficient

try:
    from trogon import tui
except ImportError:
    tui = PassThroughDecorator()

@tui()
@click.group(...)
def cli():
    ...

but I've been unable to come up with a suitable PassThroughDecorator?

willmcgugan commented 1 year ago

Would this work?

tui = lambda func: func
cariaso commented 1 year ago

yup. my sincere thanks for the answer, and much general python awesomeness

cariaso commented 1 year ago

I take back the 'yup'. That does not handle the parens.

import click
try:
    from trogon import tui
except ModuleNotFoundError:
    print("using noop trogon tui")
    tui = lambda func: func

@tui()
@click.group(...)
def cli():
    ...

using noop trogon tui Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in _run_code File "/path/to/main.py", line 13, in @tui() ^^^^^ TypeError: () missing 1 required positional argument: 'func'

the code you suggested does work for

@tui

but not

@tui()
fresh2dev commented 1 year ago

ref: https://stackoverflow.com/a/73275170

try:
    from trogon import tui
except ModuleNotFoundError:
    def tui(f=None, *args, **kwargs):
        def decorator(func):
            return func

        if callable(f):
            return f
        else:
            return decorator
cariaso commented 1 year ago

confirmed as successful. my thanks to @fresh2dev