Macro cpython::py_argparse [] [src]

macro_rules! py_argparse {
    ($py:expr, $fname:expr, $args:expr, $kwargs:expr, $plist:tt $body:block) => { ... };
}

This macro is used to parse a parameter list into a set of variables.

Syntax: py_argparse!(py, fname, args, kwargs, (parameter-list) { body })

  • py: the Python token
  • fname: expression of type Option<&str>: Name of the function used in error messages.
  • args: expression of type &PyTuple: The position arguments
  • kwargs: expression of type Option<&PyDict>: The named arguments
  • parameter-list: a comma-separated list of parameter declarations. Parameter declarations have one of these formats:

    1. name
    2. name: ty
    3. name: ty = default_value
    4. *name
    5. *name : ty
    6. **name
    7. **name : ty

    The types used must implement the FromPyObject trait. If no type is specified, the parameter implicitly uses &PyObject (format 1), &PyTuple (format 4) or &PyDict (format 6). If a default value is specified, it must be a compile-time constant

  • body: expression of type PyResult<_>. The extracted argument values are available in this scope.

py_argparse!() expands to code that extracts values from args and kwargs and assigns them to the parameters. If the extraction is successful, py_argparse!() evaluates the body expression and returns of that evaluation. If extraction fails, py_argparse!() returns a failed PyResult without evaluating body.

The py_argparse!() macro special-cases reference types (when ty starts with a & token): In this case, the macro uses the RefFromPyObject trait instead of the FromPyObject trait. When using at least one reference parameter, the body block is placed within a closure, so return statements might behave unexpectedly in this case. (this only affects direct use of py_argparse!; py_fn! is unaffected as the body there is always in a separate function from the generated argument-parsing code).