Repository navigation
BUG: Allow string/path lists for multi-value Python API arguments #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
axel-grc
wants to merge
3
commits into
RTKConsortium:main
Choose a base branch
from
axel-grc:argparse
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,131 +1,25 @@ | ||
| import argparse | ||
| import itk | ||
| from itk import PCT as pct | ||
| import inspect | ||
| from typing import Optional | ||
| import difflib | ||
| import re | ||
| from itk import pctConfig | ||
| from itk.rtkargumentparser import RTKArgumentParser | ||
|
|
||
| __all__ = ["PCTArgumentParser"] | ||
|
|
||
|
|
||
| class PCTHelpFormatter(argparse.ArgumentDefaultsHelpFormatter): | ||
| def _format_usage(self, usage, actions, groups, prefix=None): | ||
| if prefix is None: | ||
| prefix = pct.__version__ + "\n\nusage: " | ||
| return super()._format_usage(usage, actions, groups, prefix) | ||
| """PCT application argument parser. | ||
|
|
||
| ``PCTArgumentParser`` reuses :class:`RTKArgumentParser` and only overrides | ||
| the version string so that ``--version`` reports PCT's version. | ||
| """ | ||
|
|
||
| class PCTArgumentParser(argparse.ArgumentParser): | ||
| def __init__(self, description=None, **kwargs): | ||
| super().__init__(description=description, **kwargs) | ||
| self.formatter_class = PCTHelpFormatter | ||
| # allow negative numeric tokens to be treated as values, not options. This mirrors CPython behavior in python 3.14 | ||
| self._negative_number_matcher = re.compile(r"-\.?\d") | ||
| self.add_argument("-V", "--version", action="version", version=pct.__version__) | ||
|
|
||
| def build_signature(self) -> inspect.Signature: | ||
| """Build a compact Python signature: only required kwargs + **kwargs.""" | ||
| required_params = [] | ||
| for action in self._actions: | ||
| name = getattr(action, "dest", None) | ||
| if not name or name in ("help", "version"): | ||
| continue | ||
| if getattr(action, "required", False): | ||
| required_params.append( | ||
| inspect.Parameter(name=name, kind=inspect.Parameter.KEYWORD_ONLY) | ||
| ) | ||
| # Add catch-all for the many optional CLI options to keep help inline | ||
| var_kw = inspect.Parameter("kwargs", kind=inspect.Parameter.VAR_KEYWORD) | ||
| return inspect.Signature(required_params + [var_kw]) | ||
| __all__ = ["PCTArgumentParser"] | ||
|
|
||
| def build_usage_examples(self, app_name: Optional[str] = None) -> str: | ||
| """Return a Usage examples block for Python help().""" | ||
| name = app_name or self.prog | ||
| # Collect required destinations | ||
| req = [ | ||
| a.dest | ||
| for a in self._actions | ||
| if getattr(a, "required", False) | ||
| and a.dest | ||
| and a.dest not in ("help", "version") | ||
| ] | ||
| shell = f"{name}(\"{' '.join([f'--{d} {d.upper()}' for d in req])}\")" | ||
| py = f"{name}({', '.join([f'{d}={d.upper()}' for d in req])})" | ||
| return "Usage:\n" f" • Shell-style: {shell}\n" f" • Python API: {py}\n\n" | ||
|
|
||
| def apply_signature(self, func): | ||
| """Apply the built signature to a callable and return it.""" | ||
| func.__signature__ = self.build_signature() | ||
| return func | ||
| class PCTArgumentParser(RTKArgumentParser): | ||
| """Argument parser for PCT Python applications. | ||
|
|
||
| def parse_args(self, args=None, namespace=None): | ||
| """Parse args with optional single-token comma list support for multi-value options. | ||
| Supported forms: | ||
| --opt A B C (space separated) | ||
| --opt A,B,C (single token, comma separated) | ||
| """ | ||
| neutralized = {} | ||
| for action in self._actions: | ||
| dest = getattr(action, "dest", None) | ||
| if not dest or dest in ("help", "version"): | ||
| continue | ||
| nargs = getattr(action, "nargs", None) | ||
| if nargs != "+": | ||
| continue | ||
| t = getattr(action, "type", None) | ||
| if t and t is not str: | ||
| neutralized[dest] = t | ||
| action.type = str | ||
| namespace = super().parse_args(args, namespace) | ||
| for action in self._actions: | ||
| dest = getattr(action, "dest", None) | ||
| if dest not in neutralized: | ||
| continue | ||
| caster = neutralized[dest] | ||
| val = getattr(namespace, dest, None) | ||
| if isinstance(val, list): | ||
| # Case 1: user supplied a single token containing commas (e.g. "1,2,3"). | ||
| # Split on commas, strip whitespace, drop empty pieces, then cast each element. | ||
| if len(val) == 1 and isinstance(val[0], str) and "," in val[0]: | ||
| pieces = [s for s in (p.strip() for p in val[0].split(",")) if s] | ||
| setattr(namespace, dest, [caster(p) for p in pieces]) | ||
| else: | ||
| # Case 2: normal space-separated form (e.g. "1 2 3"). Just cast every token. | ||
| setattr(namespace, dest, [caster(tk) for tk in val]) | ||
| action.type = neutralized[dest] | ||
| return namespace | ||
| Reuses ``RTKArgumentParser`` and only overrides the version string so that | ||
| ``--version`` reports PCT's version. | ||
| """ | ||
|
|
||
| def parse_kwargs(self, func_name: Optional[str] = None, **kwargs): | ||
| """Convert Python kwargs to argv and parse them. | ||
| Lists/tuples for multi-value options are serialized as a single comma token.""" | ||
| actions = { | ||
| a.dest: a | ||
| for a in self._actions | ||
| if a.dest and a.dest not in ("help", "version") | ||
| } | ||
| for key in kwargs: | ||
| if key not in actions: | ||
| matches = difflib.get_close_matches( | ||
| key, actions.keys(), n=3, cutoff=0.5 | ||
| ) | ||
| name = func_name or self.prog or "function" | ||
| msg = f"{name}() got an unexpected keyword argument '{key}'" | ||
| if matches: | ||
| msg += f"\nDid you mean: {', '.join(matches)}?" | ||
| else: | ||
| msg += f"\nValid arguments are: {', '.join(sorted(actions.keys()))}" | ||
| raise TypeError(msg) | ||
| argv = [] | ||
| for key, val in kwargs.items(): | ||
| action = actions[key] | ||
| opt_strings = list(action.option_strings) | ||
| flag = next((o for o in opt_strings if o.startswith("--")), opt_strings[0]) | ||
| if isinstance(val, bool): | ||
| if val: | ||
| argv.append(flag) | ||
| elif isinstance(val, (list, tuple)): | ||
| argv += [flag, ",".join(map(str, val))] | ||
| else: | ||
| argv += [flag, str(val)] | ||
| return self.parse_args(argv) | ||
| def __init__(self, description=None, version=None, **kwargs): | ||
| super().__init__( | ||
| description=description, | ||
| version=version or pctConfig.PCT_GLOBAL_VERSION_STRING, | ||
| **kwargs, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import pytest | ||
| import itk | ||
| from itk import PCT as pct | ||
| from itk import RTK as rtk | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def parser(): | ||
| p = pct.PCTArgumentParser() | ||
| p.add_argument("--string-single", type=str, required=True) | ||
| p.add_argument("--number-single", type=int, required=True) | ||
| p.add_argument("--string-many", type=str, nargs="+", required=True) | ||
| p.add_argument("--number-many", type=int, nargs="+", required=True) | ||
| return p | ||
|
|
||
|
|
||
| def assert_args(args): | ||
| assert args.string_single == "a" | ||
| assert args.number_single == 1 | ||
| assert args.string_many == ["a", "b", "c"] | ||
| assert args.number_many == [1, 2, 3] | ||
|
|
||
|
|
||
| def test_parser_inherits_from_rtk(): | ||
| assert issubclass(pct.PCTArgumentParser, rtk.RTKArgumentParser) | ||
|
|
||
|
|
||
| def test_version_flag_uses_pct_version(parser): | ||
| assert parser._version == pct.__version__ | ||
|
|
||
|
|
||
| def test_verbose_flag_inherited(parser): | ||
| args = parser.parse_args( | ||
| [ | ||
| "--string-single", | ||
| "a", | ||
| "--number-single", | ||
| "1", | ||
| "--string-many", | ||
| "a,b,c", | ||
| "--number-many", | ||
| "1,2,3", | ||
| "-v", | ||
| ] | ||
| ) | ||
| assert args.verbose is True | ||
| assert_args(args) | ||
|
|
||
|
|
||
| def test_pctargumentparser_cli(parser): | ||
| args = parser.parse_args( | ||
| [ | ||
| "--string-single", | ||
| "a", | ||
| "--number-single", | ||
| "1", | ||
| "--string-many", | ||
| "a,b,c", | ||
| "--number-many", | ||
| "1,2,3", | ||
| ] | ||
| ) | ||
| assert_args(args) | ||
|
|
||
|
|
||
| def test_pctargumentparser_cli_commas(parser): | ||
| args = parser.parse_args( | ||
| [ | ||
| "--string-single", | ||
| "a", | ||
| "--number-single", | ||
| "1", | ||
| "--string-many", | ||
| "a", | ||
| "b", | ||
| "c", | ||
| "--number-many", | ||
| "1", | ||
| "2", | ||
| "3", | ||
| ] | ||
| ) | ||
| assert_args(args) | ||
|
|
||
|
|
||
| def test_pctargumentparser_python(parser): | ||
| args = parser.parse_kwargs( | ||
| string_single="a", | ||
| number_single=1, | ||
| string_many=["a", "b", "c"], | ||
| number_many=[1, 2, 3], | ||
| ) | ||
| assert_args(args) | ||
|
|
||
|
|
||
| def test_pctargumentparser_python_commas(parser): | ||
| args = parser.parse_kwargs( | ||
| string_single="a", number_single=1, string_many="a,b,c", number_many="1,2,3" | ||
| ) | ||
| assert_args(args) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Perhaps we could remove all tests from this file except those two, are it is already tested in RTK?
RTKConsortium/RTK@9ad6c5d