Context: Task-oriented parser context

class invoke.parser.context.Context(name=None, aliases=(), args=())

Parsing context with knowledge of flags & their format.

Generally associated with the core program or a task.

When run through a parser, will also hold runtime values filled in by the parser.

Create a new Context named name, with aliases.

name is optional, and should be a string if given. It’s used to tell Context objects apart, and for use in a Parser when determining what chunk of input might belong to a given Context.

aliases is also optional and should be an iterable containing strings. Parsing will honor any aliases when trying to “find” a given context in its input.

May give one or more args, which is a quick alternative to calling for arg in args: self.add_arg(arg) after initialization.

add_arg(*args, **kwargs)

Adds given Argument (or constructor args for one) to this context.

The Argument in question is added to the following dict attributes:

  • args: “normal” access, i.e. the given names are directly exposed as keys.
  • flags: “flaglike” access, i.e. the given names are translated into CLI flags, e.g. "foo" is accessible via flags['--foo'].
  • inverse_flags: similar to flags but containing only the “inverse” versions of boolean flags which default to True. This allows the parser to track e.g. --no-myflag and turn it into a False value for the myflag Argument.
as_kwargs

This context’s arguments’ values keyed by their .name attribute.

Results in a dict suitable for use in Python contexts, where e.g. an arg named foo-bar becomes accessible as foo_bar.

help_for(flag)

Return 2-tuple of (flag-spec, help-string) for given flag.

help_tuples()

Return sorted iterable of help tuples for all member Arguments.

Sorts like so:

  • General sort is alphanumerically
  • Short flags win over long flags
  • Arguments with only long flags and no short flags will come first.
  • When an Argument has multiple long or short flags, it will sort using the most favorable (lowest alphabetically) candidate.

This will result in a help list like so:

--alpha, --zeta # 'alpha' wins
--beta
-a, --query # short flag wins
-b, --argh
-c
invoke.parser.context.flag_key(x)

Obtain useful key list-of-ints for sorting CLI flags.

Previous topic

Argument: CLI arguments/flags

Next topic

Parser: Core parsing state machine

This Page