I'm currently migrating some Python functions to be used with the Typer library for a CLI application. Previously, these functions worked well with default parameters, but I'm encountering issues when applying Typer's argument and option decorators, specifically when dealing with default parameter values. I am using Python 3.10
.
Here's an example of my code where the issue occurs:
main.py:
import typer
app = typer.Typer()
log_level_arg = typer.Argument(default="debug", help="The output logging level. This can be one of: debug, info, warning, error, and critical.")
@app.command()
def view(log_level: str = log_level_arg):
"""
View IP address of switch in environment if it exists
"""
print("log level:")
print(log_level)
print(type(log_level))
@app.command()
def view_old(log_level: str = "debug"):
print("log level:")
print(log_level)
print(type(log_level))
print("view:")
view()
print()
print("view old:")
view_old()
Running python main.py view
outputs:
python main.py view
view:
log level:
<typer.models.ArgumentInfo object at 0x7f9804e4ceb0>
<class 'typer.models.ArgumentInfo'>
view old:
log level:
debug
<class 'str'>
log level:
debug
<class 'str'>
This bit here is the troublesome part:
view:
log level:
<typer.models.ArgumentInfo object at 0x7f9804e4ceb0>
<class 'typer.models.ArgumentInfo'>
Instead of the log_level argument being recognized as a string with the default value "debug," it's being treated as a typer.models.ArgumentInfo object. This behavior is unexpected and causes subsequent functionality that depends on log_level being a string (e.g., lower() method calls) to fail.
So my question: I guess I can workaround this with additional functions that just wrap the existing ones, but is there perhaps a way to avoid this and do this natively?
Nope not natively possible according to https://github.com/tiangolo/typer/issues/279 though there are workarounds mentioned in that thread.