Skip to main content

dargparser - the typed argparser with dataclasses

Build Status PyPI Version Conda Version Supported Python Versions Code Size Code Style

A lean and hackable typed argument parser based on dataclasses. For deep learning research and everything else.

Quickstart

Install dargparser with pip:

pip install dargparser

or conda/mamba:

conda install -c conda-forge dargparser

Usage

Simply define a dataclass with your arguments and corresponding types. You can use the dArg utility to define default values, help texts or aliases. All information is additionally used to display a semantically rich help message with the --help / -h flag.

from dataclasses import dataclass
from dargparser import dargparse, dArg, Choice

@dataclass
class Args:
    learning_rate: float = dArg(aliases="--lr", help="Required argument (no default).")
    data_path: str = dArg(default="./data/", aliases=["--data", "-d"])
    extra_data: str | None = dArg(default=None)
    epochs: int = dArg(default=42)
    cuda: bool = dArg(default=True, help="We automatically create a `--no_<arg>` flag for bools.")
    precision: Choice[32, 16, 8, "bf16", "tf32"] = dArg(default=32, help="Choices with mixed types are supported.")
    some_list_arg: list[int] = dArg(default=[1, 2, 3])

args = dargparse(Args)

# `args` now contains the values passed in via the command line
# `args` has type hints that VSCode (or PyCharm) will use for auto-completion
args.learning_rate

Everything can be defined in a single place and you get strong typing of your arguments for free! Using the example above:

# Calling your script from the command line with these arguments...
example_cmd_args = "--lr 1e-4 -d ./special-data/ --epochs 1 --precision 16 --some_list_arg 0 1 42"

# ...would produce these values for `args`:
Args(learning_rate=0.0001, data_path='./special-data/', extra_data=None, epochs=1, cuda=True, precision=16, some_list_arg=[0, 1, 42])

Advanced Usage

Required arguments without a default value, alias or help text do not need dArg:

@dataclass
class Args:
    learning_rate: float
    ...

List args: You can easily specify arguments that take multiple values as follows (behavior is similar to argparse's nargs="+"). Note that the default values should also be lists in this case.

@dataclass
class Args:
    required_list: list[int] = dArg(help="Required.")
    empty_default_list: list[int] = dArg(default=[], help="Empty list as default.")
    custom_default_list: list[int] = dArg(default=[1, 2, 3])

List + Choice combindation: You can combine list and Choice to allow the selection of an arbitrary number of values from a predefined set.

@dataclass
class Args:
    datasets: list[Choice["mnist", "cifar10", "imagenet"]] = dArg(default=["mnist", "cifar10"])

Config files: We support optionally reading arguments from a config file. By default, we read a config file specified in the CLI via the "--cfg" flag. The file is expected to contain lines of single flag-argument pairs, like you would specify them in the command line:

--argument value
--argument_two 42
--list_argument item1 item2 item3

If an argument is present in the config file and also specified via the CLI, we prefer the value in the CLI.

You can also use a different flag (e.g. "--config") if you like.

from dargparser import dargparse, dArg

@dataclass
class Args:
    lorem_arg: str = dArg(default="ipsum")

args = dargparse(Args, config_flag="--config")

Multiple dataclasses: To seperate concerns, you can split your arguments into multiple dataclasses, e.g. TrainingArgs, ModelArgs, and DataArgs.

@dataclass
class TrainingArgs:
    epochs: int = dArg(default=5)
    ...

@dataclass
class ModelArgs:
    model: Choice["roberta-base", "xlm-roberta-base"] = dArg(default="roberta-base")
    ...

@dataclass
class DataArgs:
    data_path: str = dArg(aliases="--data")
    ...

# the arguments parsed from the CLI are now split into the respective variables
training_args, model_args, data_args = dargparse(TrainingArgs, ModelArgs, DataArgs)

Formalities

This project is a fork of the HfArgparser from the HuggingFace transformers repository, with added features such as:

  • Supporting aliases for command line flags
  • Supporting reading of arguments from a config file specified via the command line
  • Easy specification of choices via Literal and Choice
  • Supporting mixed types for Literal and Enum arguments
  • Supporting nested list and Choice
  • Enriching the help message with type information and more
  • Supporting modern typing patterns such as builtin types (list[int] vs. typing.List[int]) and Optional (str | None vs. typing.Optional[str])
  • Fixing some type hint issues for VSCode

Some of these changes have already been contributed back upstream.

This code is distributed under the Apache 2.0 license, without restricting any rights reserved by the HuggingFace team.

Metadata

Release files for dargparser 1.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dargparser 1.3.0
File Size Uploaded Provenance Actions
dargparser-1.3.0.tar.gz 22.4 kB Without provenance Details for dargparser-1.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dargparser 1.3.0
File Interpreter ABI Platform Actions
dargparser-1.3.0-py3-none-any.whl Python 3 none any Details for dargparser-1.3.0-py3-none-any.whl

Total release size: 37.9 kB

Release files / dargparser-1.3.0.tar.gz

Download URL dargparser-1.3.0.tar.gz
Size 22.4 kB
Tags Source
SHA-256 checksum
How to use checksums
50dffb1e12ea7b4d5e0da5930a3d430d6d51bf96a19b0dd6a23ff99402f4a1a4
BLAKE2b-256 checksum
How to use checksums
3de252663bc81b5154cb5661f28d8fac3ed8a42b94ac6ed4d3bae86f59a0f65e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Release files / dargparser-1.3.0-py3-none-any.whl

Download URL dargparser-1.3.0-py3-none-any.whl
Size 15.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4b450071a48d97fd6910d46fad003a34dbd8983e4140e33a28cd59a444a9e5c2
BLAKE2b-256 checksum
How to use checksums
0d6b93cfe66fa2c8f71f293827fd0a82a7ef0915ddb5be8e9cd7f664869081e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.4

Security for dargparser 1.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page