{"id":19880073,"url":"https://github.com/tiskw/yadopt","last_synced_at":"2025-12-27T05:42:44.504Z","repository":{"id":263640605,"uuid":"882245036","full_name":"tiskw/yadopt","owner":"tiskw","description":"Yet another docopt, a human-friendly command line arguments parser.","archived":false,"fork":false,"pushed_at":"2025-01-12T10:55:22.000Z","size":221,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-04T08:42:43.481Z","etag":null,"topics":["argument-parser","docopt","python3"],"latest_commit_sha":null,"homepage":"https://tiskw.github.io/yadopt/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tiskw.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-02T09:38:50.000Z","updated_at":"2025-01-12T10:55:25.000Z","dependencies_parsed_at":"2025-01-22T19:15:07.394Z","dependency_job_id":null,"html_url":"https://github.com/tiskw/yadopt","commit_stats":{"total_commits":1,"total_committers":1,"mean_commits":1.0,"dds":0.0,"last_synced_commit":"0f34e61b4197df312ad7863a71f2255a9d15b760"},"previous_names":["tiskw/yadopt"],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiskw%2Fyadopt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiskw%2Fyadopt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiskw%2Fyadopt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiskw%2Fyadopt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tiskw","download_url":"https://codeload.github.com/tiskw/yadopt/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252046236,"owners_count":21685977,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["argument-parser","docopt","python3"],"created_at":"2024-11-12T17:10:11.205Z","updated_at":"2025-12-27T05:42:44.497Z","avatar_url":"https://github.com/tiskw.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"docs/images/yadopt_logo.svg\" width=\"80%\"\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/PYTHON-%3E%3D3.10-blue.svg?style=for-the-badge\u0026logo=python\u0026logoColor=white\"\u003e\n  \u0026nbsp;\n  \u003cimg src=\"https://img.shields.io/badge/LICENSE-MIT-orange.svg?style=for-the-badge\"\u003e\n  \u0026nbsp;\n  \u003cimg src=\"https://img.shields.io/badge/COVERAGE-99%25-green.svg?style=for-the-badge\"\u003e\n  \u0026nbsp;\n  \u003cimg src=\"https://img.shields.io/badge/QUALITY-10.0/10.0-yellow.svg?style=for-the-badge\"\u003e\n\u003c/div\u003e\n\nYadOpt - Yet another docopt\n====================================================================================================\n\nYadOpt is a Python re-implementation of [docopt](https://github.com/docopt/docopt) and\n[docopt-ng](https://github.com/jazzband/docopt-ng), a human-friendly command-line argument parser\nwith type hinting and utility functions. YadOpt helps you creating beautiful command-line\ninterfaces, just like docopt and docopt-ng. However, **YadOpt also supports (1) date type hinting,\n(2) conversion to dictionaries and named tuples, and (3) save and load functions**.\n\nThe following is the typical usage of YadOpt:\n\n```python\n\"\"\"\nUsage:\n    train.py \u003cconfig_path\u003e [--epochs INT] [--model STR] [--lr FLT]\n    train.py --help\n\nTrain a neural network model.\n\nArguments:\n    config_path     Path to config file.\n\nTraining options:\n    --epochs INT    The number of training epochs.   [default: 100]\n    --model STR     Neural network model name.       [default: mlp]\n    --lr FLT        Learning rate.                   [default: 1.0E-3]\n\nOther options:\n    -h, --help      Show this help message and exit.\n\"\"\"\n\nimport yadopt\n\nif __name__ == \"__main__\":\n    args = yadopt.parse(__doc__)\n    print(args)\n```\n\nPlease save the above code as `sample.py` and run it as follows:\n\n```console\n$ python3 sample.py config.toml --epochs 10 --model=cnn\nYadOptArgs(config_path=config.toml, epochs=10, model=cnn, lr=0.001, help=False)\n```\n\nIn the above code, the parsed command-line arguments are stored in the `args` variable, and you can\naccess each argument using dot notation, like `arg.config_path`. Also, the parsed command-line\narguments are typed, in other words, the `args` variable satisfies the following assertions:\n\n```python\nassert isinstance(args.config_path, pathlib.Path)\nassert isinstance(args.epochs, int)\nassert isinstance(args.model, str)\nassert isinstance(args.lr, float)\nassert isinstance(args.help, bool)\n```\n\nMore realistic examples can be found in the [examples](./examples/README.md) directory.\n\n\nInstallation\n----------------------------------------------------------------------------------------------------\n\nPlease install from [pip](https://pip.pypa.io/en/stable/).\n\n```console\n$ pip install yadopt\n```\n\n\nUsage\n----------------------------------------------------------------------------------------------------\n\n### Use `parse` function\n\nThe `yadopt.parse` function allows you to parse command-line arguments based on your docstring.\nThe function is designed to parse `sys.argv` by default, but you can explicitly specify the argument\nvector by using the second argument of the function, just like as follows:\n\n```python\n# Parse \"sys.argv\" (default behaviour).\nargs = yadopt.parse(__doc__)\n\n# Parse the given argument vector \"argv\".\nargs = yadopt.parse(__doc__, argv)\n```\n\n### Use `wrap` function\n\nYadOpt supports the decorator approach for command-line parsing by the decorator `@yadopt.wrap`\nwhich takes the same arguments as the function `yadopt.parse`.\n\n```python\n@yadopt.wrap(__doc__)\ndef main(args: yadopt.YadOptArgs, arg1: int, arg2: str):\n    ...\n\nif __name__ == \"__main__\":\n    main(arg1=1, arg2=\"2\")\n```\n\n### How to type arguments and options\n\nYadOpt provides two ways to type arguments and options: (1) type name postfix and (2) description\nhead declaration.\n\n**(1) Type name postfix**: Users can type arguments and options by adding a type name at the end of\nthe arguments/options name, such as the following:\n\n```\nOptions:\n    --opt1 FLT    Option of float type.\n    --opt2 STR    Option of string type.\n```\n\n**(2) Description head declaration**: An alternative way to type arguments and options is\nto precede the description with the type name in parentheses.\n\n```\nOptions:\n    --opt1 VAL1    (float) Option of float type.\n    --opt2 VAL2    (str)   Option of string type.\n```\n\nThe following is the list of available type names.\n\n| Data type in Python | Type name in YadOpt          |\n|---------------------|------------------------------|\n| `bool`              | bool, BOOL, boolean, BOOLEAN |\n| `int`               | int, INT, integer, INTEGER   |\n| `float`             | flt, FLT, float FLOAT        |\n| `str`               | str, STR, string, STRING     |\n| `pathlib.Path`      | path, PATH                   |\n\n\n### Dictionary and named tuple support\n\nThe returned value of `yadopt.parse` is an instance of `YadOptArgs`, a regular mutable Python class.\nHowever, sometimes a dictionary with the `get` accessor, or an immutable named tuple, may\nbe preferable. In such cases, please try `yadopt.to_dict` or `yadopt.to_namedtuple` function.\n\n```python\n# Convert the returned value to dictionary.\nargs = yadopt.to_dict(yadopt.parse(__doc__))\n\n# Convert the returned value to namedtuple.\nargs = yadopt.to_namedtuple(yadopt.parse(__doc__))\n```\n\n### Restore arguments from a file\n\nYadOpt has the ability to save parsed argument instances to a file and restore them from the file.\nThese features are useful, for example, in machine learning code, when you want to call exactly\nthe same arguments again after a previous execution. Supported file formats include TOML and JSON.\n\n```python\n# At first, create a parsed arguments (i.e. YadOptArgs instance).\nargs = yadopt.parse(__doc__)\n\n# Save the parsed arguments as a TOML file.\nyadopt.save(\"args.toml\", args)\n\n# Resotre parsed YadOptArgs instance from the TOML file.\nargs_restored = yadopt.load(\"args.toml\")\n```\n\nThe format of the TOML and JSON file is pretty straightforward \u0026mdash; what the user types\non the command line is stored in the `\"argv\"` key, and the docstring is stored in the `\"docstr\"`\nkey in the TOML/JSON file. If users want to write the TOML/JSON file manually, the author recommends\nmaking a TOML/JSON file using the `yadopt.save` function at first and investigating the contents\nof the file.\n\n\nAPI reference\n----------------------------------------------------------------------------------------------------\n\nSee [API reference page](https://tiskw.github.io/yadopt/index.html#sec4) of the online document.\n\n\nTips\n----------------------------------------------------------------------------------------------------\n\n### Merge two YadOptArgs objects\n\nThe `YadOptArgs` class, which is the return value of the `yadopt.parse` function, supports the merge\noperator `|`, similar to Python's dictionary type. This operator combines the two given YadOptArgs\nobjects into a new one. In case of a key conflict, the values from the left-hand operand are used.\n\nThis merge operator is particularly useful for implementing a feature to read an existing\nconfiguration file (for example, a file specified with the `--config` argument) and then overwrite\nthose settings with values explicitly provided in the command line arguments. For example:\n\n```python\n\"\"\"\nUsage:\n    train.py \u003cconfig_path\u003e [--epochs INT] [--model STR] [--lr FLT]\n    train.py --help\n\nTrain a neural network model.\n\nArguments:\n    config_path     Path to base config file.\n\nTraining options:\n    --epochs INT    The number of training epochs.   [default: 100]\n    --model STR     Neural network model name.       [default: mlp]\n    --lr FLT        Learning rate.                   [default: 1.0E-3]\n\nOther options:\n    -h, --help      Show this help message and exit.\n\"\"\"\n\nimport yadopt\n\nif __name__ == \"__main__\":\n\n    # Parse the command line arguments.\n    args = yadopt.parse(__doc__, ignore_default_values=True)\n\n    # Load the base config file.\n    args_base = yadopt.load(args.config_path)\n\n    # Update the parsed command line arguments.\n    args_updated = args | args_base\n    print(args_updated)\n```\n\n### More complex validations for the input command-line arguments\n\nIf you want more complex validations for the command-line arguments, the author recommends using\n[Pydantic](https://docs.pydantic.dev/latest/) for the dictionary form of the parsed object generated\nby YadOpt. Let me explain it using the sample code at the beginning of this README. Suppose you\nwant to constrain the command line argument \"lr\" such that \"0 \u003c= lr \u003c= 1.0\". The following code\nwill achieve that:\n\n```python\n\"\"\"\nUsage:\n    train.py \u003cconfig_path\u003e [--epochs INT] [--model STR] [--lr FLT]\n    train.py --help\n\nTrain a neural network model.\n\nArguments:\n    config_path     Path to config file.\n\nTraining options:\n    --epochs INT    The number of training epochs.   [default: 100]\n    --model STR     Neural network model name.       [default: mlp]\n    --lr FLT        Learning rate.                   [default: 1.0E-3]\n\nOther options:\n    -h, --help      Show this help message and exit.\n\"\"\"\n\nimport pathlib\nimport pydantic\nimport yadopt\n\nclass CommandlineArgumentsModel(pydantic.BaseModel):\n    \"\"\"\n    Pydantic model for validation.\n    \"\"\"\n    config_path: pathlib.Path\n    epochs: int\n    model: str\n    lr: float = pydantic.Field(ge=0.0, le=1.0)\n\nif __name__ == \"__main__\":\n\n    # Parse command-line arguments using YadOpt.\n    args = yadopt.parse(__doc__)\n\n    # Validate using the Pydantic model.\n    valid_args = CommandlineArgumentsModel(**yadopt.to_dict(args))\n    print(valid_args)\n```\n\n(It might be a good idea to add features to YadOpt that make it easier for users to implement\nthe above code. However, the author hasn't implemented it yet because he wants to keep\nthe dependency of YadOpt small.)\n\n\nDeveloper's note\n----------------------------------------------------------------------------------------------------\n\n### Preparation\n\nAdditional commands and Python packages are required for developers to measure the number of lines\nin the code, code quality, etc. Please run the following command (the author recommends using\n[venv](https://docs.python.org/3/library/venv.html) to avoid polluting your development\nenvironment).\n\n```console\n$ apt install cloc docker.io\n$ pip install -r requirements-dev.txt\n```\n\n### Utility commands for developers\n\nUtility commands are summarized in the Makefile. Please run `make` at the root directory of this\nrepository to see the details of the subcommands in the Makefile.\n\n```console\n$ make\nUsage:\n    make \u003ccommand\u003e\n\nBuild commands:\n    build         Build package\n    testpypi      Upload package to TestPyPi\n    pypi          Upload package to PyPi\n    install-test  Install from TestPyPi\n\nTest and code check commands:\n    check         Check the code quality\n    count         Count the lines of code\n    coverage      Measure code coverage\n\ttest          Run test on this device\n\ttestall       Run test on Docker\n\nOther commands:\n    clean         Cleanup cache files\n    help          Show this message\n```\n\n### Architecture diagram\n\n![software\\_architecture](./docs/images/software_architecture.svg)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftiskw%2Fyadopt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftiskw%2Fyadopt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftiskw%2Fyadopt/lists"}