pyTooling.Attributes.ArgParse
Attributes to describe a command line interface as decorated methods.
An application deriving from ArgParseHelperMixin declares its commands and
options as attributes on its handler methods. The mixin translates them into an argparse parser hierarchy, so
the command line’s structure is written down once - next to the code implementing it - instead of twice.
See also
DefaultHandler→ Marks the method called when no sub-command was given.
CommandHandler→ Marks the method implementing a sub-command.
Submodules
Exceptions
ArgParseError: Base-exception of all exceptions raised bypyTooling.Attributes.ArgParse.
Classes
ArgParseAttribute: Base-class for all attributes to describe aargparse-base command line argument parser._HandlerMixin: A mixin-class that offers a class field for a reference to a handler method and a matching property.CommandLineArgument: Base-class for all Argument classes.CommandGroupAttribute: Experimental attribute to group sub-commands in groups for better readability in aprog.py --helpcall.DefaultHandler: Marks a handler method as default handler. This method is called if no sub-command is given.CommandHandler: Marks a handler method as responsible for the given command.ArgParseHelperMixin: Mixin-class to implement anargparse-base command line argument processor.
Exceptions
- exception pyTooling.Attributes.ArgParse.ArgParseError[source]
Base-exception of all exceptions raised by
pyTooling.Attributes.ArgParse.Inheritance
- __init__(*args, **kwargs)
- classmethod __new__(*args, **kwargs)
Classes
- class pyTooling.Attributes.ArgParse.ArgParseAttribute[source]
Base-class for all attributes to describe a
argparse-base command line argument parser.Inheritance
- classmethod GetAttributes(method, includeSubClasses=True)
Returns attached attributes of this kind for a given method.
- Parameters:
method (
MethodType) – Method to search attributes for.includeSubClasses (
bool) – Optional, ifTrue, attributes of derived attribute classes are included too.
- Return type:
- Returns:
Tuple of attached attributes of this kind.
- Raises:
TypeError – If the method’s attribute field is not a list.
- classmethod GetClasses(scope=None, subclassOf=None)
Return a generator for all classes, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.subclassOf- when the item is a subclass ofsubclassOf.
- Parameters:
scope (
Union[type,ModuleType,None]) – Optional, class or module the classes have to be nested in or defined in;Noneaccepts every class.subclassOf (
Optional[type]) – Optional, an attribute class or tuple thereof, to filter for that attribute type or subtype.
- Return type:
- Returns:
A sequence of classes where this attribute is attached to.
- classmethod GetFunctions(scope=None)
Return a generator for all functions, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- Parameters:
scope (
Optional[type]) – Optional, module the functions have to be defined in;Noneaccepts every function.- Return type:
- Returns:
A sequence of functions where this attribute is attached to.
- Raises:
NotImplementedError – If this abstract method is not overridden by a derived class.
- classmethod GetMethods(scope=None)
Return a generator for all methods, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- property Scope: AttributeScope
Read-only property to access the scope this attribute searches in (
_scope).- Returns:
The scope this attribute searches in.
- static _AppendAttribute(entity, attribute)
Append an attribute to a language entity (class, method, function).
Hint
This method can be used in attribute groups to apply multiple attributes within
__call__method.class GroupAttribute(Attribute): def __call__(self, entity: Entity) -> Entity: self._AppendAttribute(entity, SimpleAttribute(...)) self._AppendAttribute(entity, SimpleAttribute(...)) return entity
- __call__(entity)
Attributes get attached to an entity (function, class, method) and an index is updated at the attribute for reverse lookups.
- _scope: ClassVar[AttributeScope] = 7
Allowed language construct this attribute can be used with.
- class pyTooling.Attributes.ArgParse._HandlerMixin[source]
A mixin-class that offers a class field for a reference to a handler method and a matching property.
Inheritance
- property Handler: Callable[[...], Any]
Read-only property to access the handler method (
_handler).- Returns:
The method called to handle the command.
- classmethod GetMethodsWithAttributes(predicate: Nullable[TAttributeFilter[TAttr]] = None) dict[Callable[..., Any], tuple[Attribute, ...]]
Return the class’ methods that carry at least one matching attribute.
- Parameters:
predicate (Nullable[TAttributeFilter[TAttr]]) – Optional, an attribute class, an iterable of attribute classes, or
Noneto accept every attribute.- Return type:
dict[Callable[…, Any], tuple[Attribute, …]]
- Returns:
Dictionary of methods and the matching attributes attached to them.
- Raises:
ValueError – If an element of parameter ‘predicate’ is not a sub-class of
Attribute.ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.
- class pyTooling.Attributes.ArgParse.CommandLineArgument[source]
Base-class for all Argument classes.
An argument instance can be converted via
AsArgumentto a single string value or a sequence of string values (tuple) usable e.g. withsubprocess.Popen. Each argument class implements at least onepatternparameter to specify how argument are formatted.There are multiple derived formats supporting:
commands
→CommandHandlersimple names (flags)
→FlagArgument,BooleanFlagsimple values (valued flags)
→StringArgument,PathArgumentnames and values
→ValuedFlag,OptionalValuedFlagkey-value pairs
→NamedKeyValuePairsArgument
Inheritance
- __init__(*args, **kwargs)[source]
Initializes a command line argument.
This base-class collects the parameters
add_argument()will be called with; the derived classes assemble them from named parameters instead.- Parameters:
args (
Any) – Positional parameters forwarded toadd_argument().kwargs (
Any) – Named parameters forwarded toadd_argument().
- Return type:
None
- _args: tuple[Any, ...]
Positional parameters forwarded to
add_argument().
- _kwargs: dict[str, Any]
Named parameters forwarded to
add_argument().
- property Args: tuple[Any, ...]
A tuple of additional positional parameters (
*args) passed to the attribute. These additional parameters are passed without modification toArgumentParser.- Returns:
Tuple of positional parameters.
- property KWArgs: dict[str, Any]
A dictionary of additional named parameters (
**kwargs) passed to the attribute. These additional parameters are passed without modification toArgumentParser.- Returns:
Dictionary of named parameters.
- classmethod GetAttributes(method, includeSubClasses=True)
Returns attached attributes of this kind for a given method.
- Parameters:
method (
MethodType) – Method to search attributes for.includeSubClasses (
bool) – Optional, ifTrue, attributes of derived attribute classes are included too.
- Return type:
- Returns:
Tuple of attached attributes of this kind.
- Raises:
TypeError – If the method’s attribute field is not a list.
- classmethod GetClasses(scope=None, subclassOf=None)
Return a generator for all classes, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.subclassOf- when the item is a subclass ofsubclassOf.
- Parameters:
scope (
Union[type,ModuleType,None]) – Optional, class or module the classes have to be nested in or defined in;Noneaccepts every class.subclassOf (
Optional[type]) – Optional, an attribute class or tuple thereof, to filter for that attribute type or subtype.
- Return type:
- Returns:
A sequence of classes where this attribute is attached to.
- classmethod GetFunctions(scope=None)
Return a generator for all functions, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- Parameters:
scope (
Optional[type]) – Optional, module the functions have to be defined in;Noneaccepts every function.- Return type:
- Returns:
A sequence of functions where this attribute is attached to.
- Raises:
NotImplementedError – If this abstract method is not overridden by a derived class.
- classmethod GetMethods(scope=None)
Return a generator for all methods, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- classmethod GetMethodsWithAttributes(predicate: Nullable[TAttributeFilter[TAttr]] = None) dict[Callable[..., Any], tuple[Attribute, ...]]
Return the class’ methods that carry at least one matching attribute.
- Parameters:
predicate (Nullable[TAttributeFilter[TAttr]]) – Optional, an attribute class, an iterable of attribute classes, or
Noneto accept every attribute.- Return type:
dict[Callable[…, Any], tuple[Attribute, …]]
- Returns:
Dictionary of methods and the matching attributes attached to them.
- Raises:
ValueError – If an element of parameter ‘predicate’ is not a sub-class of
Attribute.ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.
- property Handler: Callable[[...], Any]
Read-only property to access the handler method (
_handler).- Returns:
The method called to handle the command.
- property Scope: AttributeScope
Read-only property to access the scope this attribute searches in (
_scope).- Returns:
The scope this attribute searches in.
- static _AppendAttribute(entity, attribute)
Append an attribute to a language entity (class, method, function).
Hint
This method can be used in attribute groups to apply multiple attributes within
__call__method.class GroupAttribute(Attribute): def __call__(self, entity: Entity) -> Entity: self._AppendAttribute(entity, SimpleAttribute(...)) self._AppendAttribute(entity, SimpleAttribute(...)) return entity
- __call__(entity)
Attributes get attached to an entity (function, class, method) and an index is updated at the attribute for reverse lookups.
- _scope: ClassVar[AttributeScope] = 7
Allowed language construct this attribute can be used with.
- class pyTooling.Attributes.ArgParse.CommandGroupAttribute[source]
Experimental attribute to group sub-commands in groups for better readability in a
prog.py --helpcall.Inheritance
- __init__(groupName)[source]
Initializes a command group attribute.
- Parameters:
groupName (
str) – Name of the group the annotated commands are listed under in the help page.- Return type:
None
- property GroupName: str
Read-only property to access the name of the command group (
_groupName).- Returns:
Name of the command group.
- classmethod GetAttributes(method, includeSubClasses=True)
Returns attached attributes of this kind for a given method.
- Parameters:
method (
MethodType) – Method to search attributes for.includeSubClasses (
bool) – Optional, ifTrue, attributes of derived attribute classes are included too.
- Return type:
- Returns:
Tuple of attached attributes of this kind.
- Raises:
TypeError – If the method’s attribute field is not a list.
- classmethod GetClasses(scope=None, subclassOf=None)
Return a generator for all classes, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.subclassOf- when the item is a subclass ofsubclassOf.
- Parameters:
scope (
Union[type,ModuleType,None]) – Optional, class or module the classes have to be nested in or defined in;Noneaccepts every class.subclassOf (
Optional[type]) – Optional, an attribute class or tuple thereof, to filter for that attribute type or subtype.
- Return type:
- Returns:
A sequence of classes where this attribute is attached to.
- classmethod GetFunctions(scope=None)
Return a generator for all functions, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- Parameters:
scope (
Optional[type]) – Optional, module the functions have to be defined in;Noneaccepts every function.- Return type:
- Returns:
A sequence of functions where this attribute is attached to.
- Raises:
NotImplementedError – If this abstract method is not overridden by a derived class.
- classmethod GetMethods(scope=None)
Return a generator for all methods, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- property Scope: AttributeScope
Read-only property to access the scope this attribute searches in (
_scope).- Returns:
The scope this attribute searches in.
- static _AppendAttribute(entity, attribute)
Append an attribute to a language entity (class, method, function).
Hint
This method can be used in attribute groups to apply multiple attributes within
__call__method.class GroupAttribute(Attribute): def __call__(self, entity: Entity) -> Entity: self._AppendAttribute(entity, SimpleAttribute(...)) self._AppendAttribute(entity, SimpleAttribute(...)) return entity
- __call__(entity)
Attributes get attached to an entity (function, class, method) and an index is updated at the attribute for reverse lookups.
- _scope: ClassVar[AttributeScope] = 7
Allowed language construct this attribute can be used with.
- class pyTooling.Attributes.ArgParse.DefaultHandler[source]
Marks a handler method as default handler. This method is called if no sub-command is given.
Attention
It’s an error, if more than one method is annotated with this attribute.
Inheritance
- __call__(func)[source]
Apply this attribute to the handler method.
The handler method is stored in
_handler.
- classmethod GetAttributes(method, includeSubClasses=True)
Returns attached attributes of this kind for a given method.
- Parameters:
method (
MethodType) – Method to search attributes for.includeSubClasses (
bool) – Optional, ifTrue, attributes of derived attribute classes are included too.
- Return type:
- Returns:
Tuple of attached attributes of this kind.
- Raises:
TypeError – If the method’s attribute field is not a list.
- classmethod GetClasses(scope=None, subclassOf=None)
Return a generator for all classes, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.subclassOf- when the item is a subclass ofsubclassOf.
- Parameters:
scope (
Union[type,ModuleType,None]) – Optional, class or module the classes have to be nested in or defined in;Noneaccepts every class.subclassOf (
Optional[type]) – Optional, an attribute class or tuple thereof, to filter for that attribute type or subtype.
- Return type:
- Returns:
A sequence of classes where this attribute is attached to.
- classmethod GetFunctions(scope=None)
Return a generator for all functions, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- Parameters:
scope (
Optional[type]) – Optional, module the functions have to be defined in;Noneaccepts every function.- Return type:
- Returns:
A sequence of functions where this attribute is attached to.
- Raises:
NotImplementedError – If this abstract method is not overridden by a derived class.
- classmethod GetMethods(scope=None)
Return a generator for all methods, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- classmethod GetMethodsWithAttributes(predicate: Nullable[TAttributeFilter[TAttr]] = None) dict[Callable[..., Any], tuple[Attribute, ...]]
Return the class’ methods that carry at least one matching attribute.
- Parameters:
predicate (Nullable[TAttributeFilter[TAttr]]) – Optional, an attribute class, an iterable of attribute classes, or
Noneto accept every attribute.- Return type:
dict[Callable[…, Any], tuple[Attribute, …]]
- Returns:
Dictionary of methods and the matching attributes attached to them.
- Raises:
ValueError – If an element of parameter ‘predicate’ is not a sub-class of
Attribute.ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.
- property Handler: Callable[[...], Any]
Read-only property to access the handler method (
_handler).- Returns:
The method called to handle the command.
- property Scope: AttributeScope
Read-only property to access the scope this attribute searches in (
_scope).- Returns:
The scope this attribute searches in.
- static _AppendAttribute(entity, attribute)
Append an attribute to a language entity (class, method, function).
Hint
This method can be used in attribute groups to apply multiple attributes within
__call__method.class GroupAttribute(Attribute): def __call__(self, entity: Entity) -> Entity: self._AppendAttribute(entity, SimpleAttribute(...)) self._AppendAttribute(entity, SimpleAttribute(...)) return entity
- _scope: ClassVar[AttributeScope] = 7
Allowed language construct this attribute can be used with.
- class pyTooling.Attributes.ArgParse.CommandHandler[source]
Marks a handler method as responsible for the given command.
A sub-command parser is constructed for it with
add_subparsers().Inheritance
- __init__(command, help='', **kwargs)[source]
Initializes a command handler attribute.
- Parameters:
command (
str) – Name of the sub-command on the command line.help (
str) – Optional, help text shown for the sub-command. Default:"".kwargs (
Any) – Named parameters forwarded toadd_subparsers().
- Return type:
None
- _args: tuple[Any, ...]
Positional parameters forwarded to
add_subparsers().
- _kwargs: dict[str, Any]
Named parameters forwarded to
add_subparsers().
- __call__(func)[source]
Apply this attribute to the handler method.
The handler method is stored in
_handler.
- property Command: str
Read-only property to access the command a sub-command parser adheres to (
_command).- Returns:
Name of the command.
- property Args: tuple[Any, ...]
A tuple of additional positional parameters (
*args) passed to the attribute. These additional parameters are passed without modification toArgumentParser.- Returns:
Tuple of positional parameters.
- property KWArgs: dict[str, Any]
A dictionary of additional named parameters (
**kwargs) passed to the attribute. These additional parameters are passed without modification toArgumentParser.- Returns:
Dictionary of named parameters.
- classmethod GetAttributes(method, includeSubClasses=True)
Returns attached attributes of this kind for a given method.
- Parameters:
method (
MethodType) – Method to search attributes for.includeSubClasses (
bool) – Optional, ifTrue, attributes of derived attribute classes are included too.
- Return type:
- Returns:
Tuple of attached attributes of this kind.
- Raises:
TypeError – If the method’s attribute field is not a list.
- classmethod GetClasses(scope=None, subclassOf=None)
Return a generator for all classes, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.subclassOf- when the item is a subclass ofsubclassOf.
- Parameters:
scope (
Union[type,ModuleType,None]) – Optional, class or module the classes have to be nested in or defined in;Noneaccepts every class.subclassOf (
Optional[type]) – Optional, an attribute class or tuple thereof, to filter for that attribute type or subtype.
- Return type:
- Returns:
A sequence of classes where this attribute is attached to.
- classmethod GetFunctions(scope=None)
Return a generator for all functions, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- Parameters:
scope (
Optional[type]) – Optional, module the functions have to be defined in;Noneaccepts every function.- Return type:
- Returns:
A sequence of functions where this attribute is attached to.
- Raises:
NotImplementedError – If this abstract method is not overridden by a derived class.
- classmethod GetMethods(scope=None)
Return a generator for all methods, where this attribute is attached to.
- The resulting item stream can be filtered by:
scope- when the item is a nested class in scopescope.
- classmethod GetMethodsWithAttributes(predicate: Nullable[TAttributeFilter[TAttr]] = None) dict[Callable[..., Any], tuple[Attribute, ...]]
Return the class’ methods that carry at least one matching attribute.
- Parameters:
predicate (Nullable[TAttributeFilter[TAttr]]) – Optional, an attribute class, an iterable of attribute classes, or
Noneto accept every attribute.- Return type:
dict[Callable[…, Any], tuple[Attribute, …]]
- Returns:
Dictionary of methods and the matching attributes attached to them.
- Raises:
ValueError – If an element of parameter ‘predicate’ is not a sub-class of
Attribute.ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.
- property Handler: Callable[[...], Any]
Read-only property to access the handler method (
_handler).- Returns:
The method called to handle the command.
- property Scope: AttributeScope
Read-only property to access the scope this attribute searches in (
_scope).- Returns:
The scope this attribute searches in.
- static _AppendAttribute(entity, attribute)
Append an attribute to a language entity (class, method, function).
Hint
This method can be used in attribute groups to apply multiple attributes within
__call__method.class GroupAttribute(Attribute): def __call__(self, entity: Entity) -> Entity: self._AppendAttribute(entity, SimpleAttribute(...)) self._AppendAttribute(entity, SimpleAttribute(...)) return entity
- _scope: ClassVar[AttributeScope] = 7
Allowed language construct this attribute can be used with.
- class pyTooling.Attributes.ArgParse.ArgParseHelperMixin[source]
Mixin-class to implement an
argparse-base command line argument processor.Inheritance
- __init__(**kwargs)[source]
The mixin-constructor expects an optional list of named parameters which are passed without modification to the
ArgumentParserconstructor.- Parameters:
kwargs (
Any) – Named parameters forwarded to theArgumentParserconstructor.- Raises:
ArgParseError – If more than one method is marked as the default handler.
- Return type:
None
- classmethod GetMethodsWithAttributes(predicate: Nullable[TAttributeFilter[TAttr]] = None) dict[Callable[..., Any], tuple[Attribute, ...]]
Return the class’ methods that carry at least one matching attribute.
- Parameters:
predicate (Nullable[TAttributeFilter[TAttr]]) – Optional, an attribute class, an iterable of attribute classes, or
Noneto accept every attribute.- Return type:
dict[Callable[…, Any], tuple[Attribute, …]]
- Returns:
Dictionary of methods and the matching attributes attached to them.
- Raises:
ValueError – If an element of parameter ‘predicate’ is not a sub-class of
Attribute.ValueError – If parameter ‘predicate’ is neither an attribute class nor an iterable of those.
- _subParsers: dict[str, ArgumentParser]
Sub-command name to its argument parser.
- _mainParser: ArgumentParser
The main argument parser of the application.
- _PrintHelp(command=None)[source]
Helper method to print the command line parser’s help page, or the help page of one sub-command.
Attention
This method writes through the
Write***methods ofTerminalApplication, which this mixin-class does not provide, so the application class has to derive from both.- Parameters:
command (
Optional[str]) – Optional, the sub-command to print the help page for. IfNone, the main parser’s help page is printed. Default:None.- Raises:
UnfulfilledExpectationError – If the application class doesn’t also derive from
TerminalApplication.- Return type:
- Run(enableAutoComplete=True)[source]
Parse the command line arguments and call the handler method the command selects.
- _EnabledAutoComplete()[source]
Register the main parser with
argcompletefor shell completion.The package is optional: when it isn’t installed, completion is silently unavailable.
- Return type:
- _ParseArguments()[source]
Parse the command line arguments and route them to the selected handler method.
- Return type:
- _RouteToHandler(args)[source]
Call the handler method the parsed arguments select.
The handler is stored as an unbound function, so it is called with the application object as first parameter.
- property MainParser: ArgumentParser
Read-only property to access the main argument parser (
_mainParser).- Returns:
The main argument parser.
- property SubParsers: dict[str, ArgumentParser]
Read-only property to access the sub-parsers (
_subParser).- Returns:
Dictionary of command names and their sub-parsers.