Skip to content

improve arg spec guessing to allow more basic types#245

Open
snoyer wants to merge 1 commit intoneithere:masterfrom
snoyer:improve-arg-spec-guessing
Open

improve arg spec guessing to allow more basic types#245
snoyer wants to merge 1 commit intoneithere:masterfrom
snoyer:improve-arg-spec-guessing

Conversation

@snoyer
Copy link

@snoyer snoyer commented Jan 11, 2026

This PR refactors the guessing of arg specs from type hints in order to not use an hardcoded whitelist of basic types.

Currently the code first checks against a few known basic type first, then checks for the list and Literal cases, and falls back to the type being unknown/unusable.
This PR checks for list first, then the Literal case in unchanged, and the basic type case is now the fallback.

This allows the use of basic types outside of (str, int, float, bool), for example pathlib.Path which is pretty useful for CLI functions, and even custom types that are unknown to argh.


Example with Path:

from pathlib import Path
import argh


def cmd(paths: list[Path]):
    for path in paths:
        print(repr(path), "exists" if path.exists() else "does not exist")


argh.dispatch_command(cmd)
$ python cmd_paths.py /tmp /tmp/foobar
PosixPath('/tmp') exists
PosixPath('/tmp/foobar') does not exist

Example with custom type:

import re
import argh


class Color:
    def __init__(self, hex: str) -> None:
        if m := re.match(r"#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", hex):
            self.r = int(m.group(1), 16)
            self.g = int(m.group(2), 16)
            self.b = int(m.group(3), 16)
        else:
            raise ValueError(f"cannot parse color from {hex!r}")

    def __str__(self) -> str:
        return f"rgb({self.r}, {self.g}, {self.b})"


def cmd(colors: list[Color]):
    for color in colors:
        print(f"{color}")


argh.dispatch_command(cmd)
$ python cmd_colors.py "#123abc" "#abcdef"
rgb(18, 58, 188)
rgb(171, 205, 239)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant