API Reference

Smart Argument Suite

This module is an argument serialization and deserialization library that:

  • handles two-way conversions: a typed, preferably immutable argument container object (a NamedTuple or dataclass instance) <==> a command-line argv

  • enables IDE type hints and code auto-completion by using NamedTuple or dataclass

  • promotes type-safety of cli-ready arguments

The following is a simple usage example:

# Define the argument container class:
@arg_suite
class MyArg(NamedTuple):
    '''MyArg is smart and the docstring goes to description'''

    nn: List[int]  # Comments go to ArgumentParser argument help

    a_tuple: Tuple[str, int]  # Arguments without defaults are treated as "required = True"
    h_param: Dict[str, int]  # Also supports List, Set

    ###### arguments without defaults go first as required by NamedTuple ######

    l_r: float = 0.01 # Arguments with defaults are treated as "required = False"
    n: Optional[int] = None  # Optional can only default to `None`


# Create the corresponding argument container class instance from the command line argument list:
# by using
arg: ArgClass = ArgClass.__from_argv__(sys.argv[1:])  # with factory method, need the manual type hint `:ArgClass` to help IDE
# or the monkey-patched constructor of the annotated argument container class
arg = ArgClass(sys.argv[1:])  # with monkey-patched constructor with one positional argument, no manual hint needed

# Create a NamedTuple argument instance and generate its command line counterpart:
# the monkey-patched constructor only take named arguments for directly creating the NamedTuple
arg = ArgClass(nn=[200, 300], a_tuple=('t', 0), h_param={'batch_size': 1000})
# generate the corresponding command line argument list
arg.__to_argv__()

The module contains the following public classes/functions:

  • arg_suite – The main entry point for Smart Argument Suite. As the

    example above shows, this decorator will attach an ArgSuite instance to the argument container class NamedTuple or dataclass and patch it.

  • PrimitiveHandlerAddon – The base class to deal some basic operation on primitive types,

    and users can implement their owns to change the behavior.

  • TypeHandler – The base class to handle types, users can extend to expand the

    support or change existing behaviors.

All other classes and methods in this module are considered implementation details.

class smart_arg.LateInit

special singleton/class to mark late initialized fields

class smart_arg.PrimitiveHandlerAddon

Primitive handler addon defines some basic operations on primitive types. Only staticmethod is expected. Users can extend/modify the primitive handling by inheriting this class.

static build_choices(arg_type)

Enumerate arg_type if possible, or return None.

Return type

Optional[Iterable[Any]]

static build_metavar(arg_type)

Define the hint string in argument help message for arg_type.

Return type

str

static build_str(arg)

Define to serialize the arg to a string.

Parameters

arg (Any type that is supported by this class) – The argument

Return type

str

Returns

The string serialization of arg

exception smart_arg.SmartArgError

Base exception for smart-arg.

class smart_arg.TypeHandler(primitive_addons)

Base type handler. A subclass typically implements gen_cli_arg for serialization and _build_other for deserialization.

gen_cli_arg(arg)

Generate command line for argument. This defines the serialization process.

Parameters

arg (Any) – value of the argument

Return type

Iterable[str]

Returns

iterable command line str

gen_kwargs(field_meta, parent_required)

Build keyword argument object KwargsType

Parameters
  • parent_required (bool) – if the parent container is required

  • field_meta (FieldMeta) – argument metadata information

Return type

SimpleNamespace

Returns

keyword argument object

smart_arg.custom_arg_suite

alias of smart_arg.ArgSuiteDecorator

smart_arg.frozenlist

alias of tuple