Skip to content

pyparam.params

module

pyparam.params

Definition of Params

Classes
  • Params Params, served as root params or subcommands</>
class

pyparam.params.Params(names=None, desc=None, prog=None, help_keys=None, help_cmds=None, help_on_void=None, help_callback=None, help_modifier=None, fullopt_keys=None, prefix='auto', arbitrary=False, theme='default', usage=None)

Params, served as root params or subcommands

Parameters
  • names (Union(str, list of str), optional) The names of this command if served as a command
  • desc (Union(list of str, str), optional) The description of the command. This will be finally compiled into a list if a string is given. The difference is, when displayed on help page, the string will be wrapped by textwrap automatically. However, each element in a given list will not be wrapped.
  • prog (str, optional) The program name
  • help_keys (Union(str, list of str), optional) The names to bring up the help information
  • help_cmds (Union(str, list of str), optional) The help command names to show help of other subcommands
  • help_on_void (str or bool, optional) Whether to show help when no arguments provided
  • help_callback (callable, optional) A function to modify the help page
  • help_modifier (callable, optional) A callback function to modify the help param/command
  • prefix (str, optional) The prefix for the arguments (see attribute Params.prefix)
  • arbitrary (str or bool, optional) Whether to parse the command line arbitrarily
  • theme (str|rich.theme.Theme) The theme to render the help page
  • usage (Union(str, list of str), optional) Some example usages
Attributes
  • arbitrary Whether parsing the command line arbitrarily
  • asssembler The asssembler to assemble the help page
  • command_groups The ordered dict of command groups
  • commands The ordered dict of registered commands
  • comp_curr (str) The current word for completion
  • comp_prev (str) The previous word matched
  • comp_shell (str) The shell where the completion will be conducted One of ['', 'bash', 'fish', 'zsh'] Obtained from environment
  • comp_words (list of str) The words have been entered before completion
  • desc (list of str) The description of the command.
  • help_cmds (list of str) The names of help subcommands to bring up help information of subcommands
  • help_keys (list of str) The names to bring up the help information.
  • help_on_void (bool) Whether show help when there is not arguments provided
  • names (list of str) The names of the commands if this serves as sub-command
  • param_groups The ordered dict of parameter groups
  • params The ordered dict of registered parameters
  • prefix The prefix for the arguments on command line - auto: Automatically determine the prefix for each argument. Basically, - for short options, and -- for long. Note that - for -vvv if v is a count option
  • prog The program name. Default: sys.argv[0]
  • prog (str) Get the program name</>
  • progvar (str) Get the program name that can be used as a variable</>
  • theme (rich.theme.Theme|str) The theme for the help page
  • uid (str) Get the uid based on the raw program name
    This is used as the prefix or suffix of some shell function names</>
  • usage The usages of this program
Methods
  • add_command(names, desc, help_keys, help_cmds, help_on_void, help_callback, help_modifier, prefix, arbitrary, theme, usage, group, force) (Params) Add a sub-command</>
  • add_param(names, default, type, desc, show, required, callback, group, force, type_frozen, argname_shorten, complete_callback, **kwargs) (Param) Add an argument</>
  • complete() (str) Yields the completions</>
  • copy(deep) (Params) Copy a Params object</>
  • from_arg(names, desc, group, default, show, force, args) Load parameters from the file specified by naargument from command line</>
  • from_dict(dict_obj, show, force) Load parameters from python dict</>
  • from_file(filename, show, force) Load parameters from file</>
  • get_command(name) (Params) Get the command object</>
  • get_param(name) (Param) Get the parameter by name</>
  • name(which) (str) Get the shortest/longest name of the parameter</>
  • namestr(sep) (str) Get all names connected with a separator.</>
  • parse(args, ignore_errors) (Namespace) Parse the arguments from the command line</>
  • print_help(exit_code, full) Print the help information and exit</>
  • shellcode(shell, python, module) (str) Generate the shell code to be integrated</>
  • to_dict() (Diot) Save the parameters/commands to file.</>
  • to_file(path, cfgtype) Save the parameters/commands to file.</>
  • values(namespace, ignore_errors) (Namespace) Get a namespace of all parameter name => value pairs or attach them to the given namespace</>
method

shellcode(shell, python=None, module=False) → str

Generate the shell code to be integrated

For bash, it should be appended to ~/.profile For zsh, it should be appended to ~/.zprofile For fish, it should be appended to ~/.config/fish/completions/%(prog)s.fish If python is provided, this should go to python.fish rather than the %(prog)s.fish

Parameters
  • shell (str) The shell to generate the code for.
  • python (str, optional) The python name or path to invoke completion.
  • module (bool, optional) Whether do completion for python -m <prog>
Raises
  • ValueError if shell is not one of bash, zsh and fish
generator

complete()

Yields the completions

Yields (str)

The strings as completion candidates

method

name(which='short')

Get the shortest/longest name of the parameter

A name is ensured to be returned. It does not mean it is the real short/long name, but just the shortest/longest name among all the names

Parameters
  • which (str, optional) Whether get the shortest or longest name Could use short or long for short.
Returns (str)

The shortest/longest name of the parameter

method

namestr(sep=', ')

Get all names connected with a separator.

Parameters
  • sep (str, optional) The separator to connect the names
Returns (str)

the connected names

method

get_param(name)

Get the parameter by name

If the parameter is under a namespace, try to get it via the namespace

Parameters
  • name (str) The name of the parameter to get (without prefix)
Returns (Param)

The parameter, None if failed

method

get_command(name)

Get the command object

Parameters
  • name (str) The name of the command to get
Returns (Params)

The command object, None if failed.

method

add_param(names, default=None, type=None, desc=None, show=None, required=None, callback=None, group=None, force=False, type_frozen=None, argname_shorten=None, complete_callback=None, **kwargs) → Param

Add an argument

Parameters
  • names (Union(str, list of str, param)) names of the argument or a parameter defined somewhere else For example, in case we want to reuse a parameter
    param = cmd1.add_param('n,name')
    # reuse it:
    cmd2.add_param(param)
    # other arguments will be ignored, except force
    
  • default (any, optional) The default value for the argument
  • type (str or type, optional) The type of the argument Including single value type and complex one - Single value types: auto, int, str, float, bool, count, py, json, reset - Complex value types: list[], ns
  • desc (Union(str, list of str), optional) The description of the argument This will be finally compiled into a list if a string is given. The difference is, when displayed on help page, the string will be wrapped by textwrap automatically. However, each element in a given list will not be wrapped.
  • show (bool, optional) Whether this should be shown on help page.
  • required (bool, optional) Whether this argument is required from the command line
  • callback (callable, optional) Callback to convert parsed values
  • group (str, optional) The group this parameter belongs to. Arguments will be grouped by this on the help page.
  • force (bool, optional) Whether to force adding parameter if it exists
  • type_frozen (bool, optional) Whether allow type overwritting from the commone line
  • argname_shorten (bool, optional) Whether show shortened name for parameter under namespace parameter
  • complete_callback (callable, optional) The callback for complete the values of the parameter
  • **kwargs Additional keyword arguments
Raises
  • PyParamNameError When parameter exists and force is false

Return: Param: The added parameter

method

add_command(names, desc='No description', help_keys='__inherit__', help_cmds='__inherit__', help_on_void='__inherit__', help_callback=None, help_modifier=None, prefix='__inherit__', arbitrary='__inherit__', theme='__inherit__', usage=None, group=None, force=False)

Add a sub-command

Parameters
  • names (Union(params, str, list of str)) list of names of this command It can also be a Params object that served as a subcommand
  • desc (Union(str, list of str), optional) description of this command
  • help_keys (Union(str, list of str), optional) help key for bring up help for this command
  • help_cmds (Union(str, list of str), optional) help command for printing help for other sub-commands of this command
  • help_on_void (str or bool, optional) whether printing help when no arguments passed
  • help_callback (callable, optional) callback to manipulate help page
  • prefix (str, optional) prefix for arguments for this command
  • theme (str or Theme, optional) The theme of help page for this command
  • usage (Union(str, list of str), optional) Usage for this command
  • group (str, optional) Group of this command
  • force (bool, optional) Force adding when command exists already.
  • arbitray whether do arbitray Parsing
Returns (Params)

The added command

method

print_help(exit_code=1, full=False)

Print the help information and exit

Parameters
  • exit_code (int, optional) The exit code or False to not exit
method

values(namespace=None, ignore_errors=False)

Get a namespace of all parameter name => value pairs or attach them to the given namespace

Parameters
  • namespace (Namespace, optional) The namespace for the values to attach to.
Returns (Namespace)

the namespace with values of all parameter name-value pairs

method

parse(args=None, ignore_errors=False)Namespace

Parse the arguments from the command line

Parameters
  • args (list of str, optional) The arguments to parse
  • ignore_errors (bool, optional) Whether to ignore errors. This is helpful to check a specific option or command, but ignore errors, such as required options not provided.

Return: Namespace: The namespace of parsed arguments

method

to_dict()

Save the parameters/commands to file.

This is helpful if the parameters/commands take time to load. Once can cache this to a file, and load it from it using from_file.

Returns (Diot)

The complied Diot of parameters and commands

method

to_file(path, cfgtype=None)

Save the parameters/commands to file.

This is helpful if the parameters/commands take time to load. Once can cache this to a file, and load it from it using from_file.

Parameters
  • path (str or Path) The path to the file
  • cfgtype (str, optional) The type of the file If not given, will inferred from the suffix of the path Supports one of yaml, toml and json
method

from_file(filename, show=True, force=False)

Load parameters from file

We support 2 types for format to load the parameters.

  • express way, which has some limitations:

    1. no command definition;
    2. no namespace parameters;
      arg = 1 # default value
      "arg$desc" = "An argument" # description
      # other attributes
      
  • full specification

    [params.arg]
    default = 1
    desc = "An argument"
    [commands.command]
    desc = "A subcommand"
    
      [commands.command.params.arg]
      default = 2
      desc = "An argument for command"
    

Parameters
  • filename (str, PathLike, or dict) path to the file
  • show (bool, optional) The default show value for parameters in the file
  • force (bool, optional) Whether to force adding params/commands
  • filetype The type of the file. If None, will infer from the filename. Supported types: ini, cfg, conf, config, yml, yaml, json, env, osenv, toml
method

from_dict(dict_obj, show=True, force=False)

Load parameters from python dict

Parameters
  • dict_obj (dict) A python dictionary to load parameters from
  • show (bool, optional) The default show value for the parameters in the dictionary
  • force (bool, optional) Whether to force adding params/commands
method

from_arg(names, desc='The configuration file.', group=None, default=None, show=True, force=False, args=None)

Load parameters from the file specified by naargument from command line

This will load the parameters from the file given by the argument, ignoring other arguments from the command line. One can overwrite some of them afterwards, and do the parsing finally.

Parameters
  • names (Union(str, list of str, parampath)) The names of the parameter or the parameter itself. If it is the parameter, other arguments are ignored
  • desc (Union(str, list of str), optional) The description of the parameter
  • group (str, optional) The group of the parameter
  • default (str or Path, optional) The default value of the file path
  • show (bool, optional) Whether those parameters should show up in the help page
  • force (bool, optional) Whether to force adding the parameters/commands
  • args (list of str, optional) The list of items to parse, otherwise parse sys.argv[1:]
method

copy(deep=False)

Copy a Params object

Parameters
  • deep (optional) Whether to copy the parameters and commands deeply
Returns (Params)

The copied params object