Skip to content

Commit

Permalink
Merge pull request #20 from explosion/fix/display-type
Browse files Browse the repository at this point in the history
  • Loading branch information
ines committed Mar 9, 2023
2 parents f883696 + e8df3d1 commit 1518784
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 5 deletions.
1 change: 1 addition & 0 deletions radicli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def get_converter(arg_type: Type) -> Optional[ConverterType]:
default=sig_defaults[param],
skip_resolve=converter is not None,
get_converter=get_converter,
has_converter=converter is not None,
)
arg.help = join_strings(arg.help, f"({format_type(arg.display_type)})")
cli_args.append(arg)
Expand Down
45 changes: 43 additions & 2 deletions radicli/tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import shutil
from zipfile import ZipFile
from pathlib import Path
from radicli import Radicli, StaticRadicli, Arg, get_arg, ArgparseArg
from radicli import Radicli, StaticRadicli, Arg, get_arg, ArgparseArg, Command
from radicli.util import CommandNotFoundError, CliParserError
from radicli.util import ExistingPath, ExistingFilePath, ExistingDirPath
from radicli.util import ExistingFilePathOrDash, DEFAULT_CONVERTERS
from radicli.util import stringify_type, get_list_converter
from radicli.util import stringify_type, get_list_converter, format_type


@contextmanager
Expand Down Expand Up @@ -912,3 +912,44 @@ def convert_generic(value: str) -> str:
new_arg = ArgparseArg.from_static_json(arg_json)
assert new_arg.type is str
assert new_arg.orig_type == stringify_type(arg.orig_type)


@pytest.mark.parametrize(
"arg_type,expected_type,expected_str",
[
(str, str, "str"),
(List[str], List[str], "List[str]"),
(Optional[List[str]], List[str], "List[str]"),
(Union[str, int], str, "str"),
(CustomGeneric, CustomGeneric, "CustomGeneric"),
(CustomGeneric[str], CustomGeneric[str], "CustomGeneric[str]"),
(ExistingFilePath, ExistingFilePath, "ExistingFilePath (Path)"),
(ZipFile, ZipFile, "ZipFile"),
],
)
def test_cli_arg_display_type(arg_type, expected_type, expected_str):
split_string = get_list_converter(str)

def convert_zipfile(value: str) -> ZipFile:
return ZipFile(value, "r")

def convert_generic(value: str) -> str:
return f"generic: {value}"

converters = {
**DEFAULT_CONVERTERS,
ZipFile: convert_zipfile, # new type with custom converter
List[str]: split_string,
CustomGeneric: convert_generic,
CustomGeneric[str]: str,
}

def test(test: arg_type):
...

cmd = Command.from_function(
"test", {"test": Arg("--test")}, test, converters=converters
)
arg = cmd.args[0]
assert arg.display_type == expected_type
assert format_type(arg.display_type) == expected_str
18 changes: 16 additions & 2 deletions radicli/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ def get_arg(
orig_type: Union[ArgTypeType, str] = None,
default: Optional[Any] = DEFAULT_PLACEHOLDER,
get_converter: Optional[Callable[[Type], Optional[ConverterType]]] = None,
has_converter: bool = False,
skip_resolve: bool = False,
) -> ArgparseArg:
"""Generate an argument to add to argparse and interpret types if possible."""
Expand All @@ -259,6 +260,7 @@ def get_arg(
help=orig_arg.help,
default=default,
orig_type=orig_type,
has_converter=has_converter,
)
if orig_arg.count:
arg.action = "count"
Expand Down Expand Up @@ -363,8 +365,20 @@ def stringify_type(arg_type: Any) -> Optional[str]:
def format_type(arg_type: Any) -> Optional[str]:
"""Get a pretty-printed string for a type."""
type_str = stringify_type(arg_type)
if isinstance(arg_type, type(NewType)) and hasattr(arg_type, "__supertype__"): # type: ignore
return f"{type_str} {arg_type.__name__}" # type: ignore
# Hacky check for cross-platform supertypes for NewType custom types
if (
(
# Python < 3.10
hasattr(arg_type, "__qualname__")
and arg_type.__qualname__.startswith("NewType")
)
# Python 3.10+
or (hasattr(arg_type, "__class__") and arg_type.__class__ is NewType)
) and (
hasattr(arg_type, "__supertype__")
): # type: ignore
supertype = stringify_type(arg_type.__supertype__) # type: ignore
return f"{type_str} ({supertype})"
return type_str


Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[metadata]
version = 0.0.15
version = 0.0.16
description = Radically lightweight command-line interfaces
url = https://github.com/explosion/radicli
author = Explosion
Expand Down

0 comments on commit 1518784

Please sign in to comment.