Skip to content

Commit

Permalink
Default values for annotation and default
Browse files Browse the repository at this point in the history
    * Allow `name` as a positional argument
    * test for __version__ extraction
  • Loading branch information
inno committed May 1, 2024
1 parent bdfe231 commit bb3d748
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 18 deletions.
27 changes: 14 additions & 13 deletions simplecli/simplecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,17 @@ class Param(inspect.Parameter):
required: bool # Exit if a value is not present

def __init__(self, *argv: Any, **kwargs: Any) -> None:
if "kind" not in kwargs:
kwargs["kind"] = inspect.Parameter.POSITIONAL_OR_KEYWORD
for required_arg in ("annotation", "name"):
if required_arg not in kwargs:
raise TypeError(
f"needs keyword-only argument '{required_arg}'"
)
kwargs["annotation"] = kwargs.pop("annotation", Empty)
kwargs["default"] = kwargs.pop("default", Empty)
kwargs["kind"] = kwargs.pop(
"kind", inspect.Parameter.POSITIONAL_OR_KEYWORD
)
# Allow 'name' as a positional parameter
if "name" not in kwargs:
if len(argv) == 0:
raise TypeError("needs 'name' argument")
kwargs["name"] = argv[0]
argv = ()
if kwargs["annotation"] not in get_args(ValueType):
if get_origin(kwargs["annotation"]) is not Union:
if kwargs["annotation"] is not Empty:
Expand All @@ -60,8 +64,6 @@ def __init__(self, *argv: Any, **kwargs: Any) -> None:
f"'{type(kwargs['annotation']).__name__}' "
"is not currently supported!"
)
kwargs["annotation"] = kwargs.pop("annotation", Empty)
kwargs["default"] = kwargs.pop("default", Empty)
param_description = str(kwargs.pop("description", ""))
param_line = str(kwargs.pop("line", ""))
param_value = kwargs.pop("value", Empty)
Expand Down Expand Up @@ -330,10 +332,8 @@ def wrap(func: Callable[..., Any]) -> None:
pos_args, kw_args = clean_args(argv)
version = func.__globals__.get("__version__", "")
if version:
params.append(
Param(name="version", annotation=Empty, internal_only=True)
)
params.append(Param(name="help", annotation=Empty, internal_only=True))
params.append(Param("version", internal_only=True))
params.append(Param("help", internal_only=True))
if "help" in kw_args:
exit(help_text(filename, params, format_docstring(func.__doc__ or "")))

Expand Down Expand Up @@ -414,6 +414,7 @@ def extract_code_params(code: Callable[..., Any]) -> list[Param]:
comment = ""
params.append(param)
param = None
# Necessary for < py3.12
if param:
params.append(param)
return params
18 changes: 18 additions & 0 deletions tests/test_extract_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,21 @@ def test_wrap_simple_value_error(monkeypatch):
@simplecli.wrap
def code(a: int):
pass


def test_wrap_version(monkeypatch):
monkeypatch.setattr(sys, "argv", ["filename", "--version"])
monkeypatch.setattr(simplecli, "_wrapped", False)
monkeypatch.setattr(simplecli, "_wrapped", False)

with pytest.raises(SystemExit) as e:
def code1(this_var: int): # stuff and things
pass
code1.__globals__["__version__"] = "1.2.3"
simplecli.wrap(code1)

help_msg = e.value.args[0]
assert re.search(r"Version: 1.2.3", help_msg)
assert not re.search(r"--this-var", help_msg)
assert not re.search(r"\(int\)", help_msg)
assert not re.search(r"stuff and things", help_msg)
11 changes: 6 additions & 5 deletions tests/test_param.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@


def test_required_arguments():
with pytest.raises(TypeError, match="annotation"):
Param()
with pytest.raises(TypeError, match="name"):
Param(annotation=str)
p = Param(name="testparam", annotation=str)
assert isinstance(p, Param)
Param()
p1 = Param(name="testparam")
assert isinstance(p1, Param)
p2 = Param("testparam")
assert isinstance(p2, Param)
assert p1 == p2


def test_equality():
Expand Down

0 comments on commit bb3d748

Please sign in to comment.