diff options
author | Eric Lin <anselor@gmail.com> | 2020-08-19 14:01:50 -0400 |
---|---|---|
committer | anselor <anselor@gmail.com> | 2021-03-18 18:26:20 -0400 |
commit | 486734e85988d0d0160147b0b44a37759c833e8a (patch) | |
tree | 3b0ef809806d86d781e869771540465cbe089e20 /cmd2/command_definition.py | |
parent | a0cb0e37878a03aa197ba502857afabb0ffad171 (diff) | |
download | cmd2-git-486734e85988d0d0160147b0b44a37759c833e8a.tar.gz |
Each CommandSet's settables are defined separately. cmd2.Cmd searches all registered CommandSets for settables.
Settables can now set any attribute on any object passed to it. The name the user sees may be set to a different value
than what the actual attribute is.
Cmd2 will now aggregate all settables on the cmd2.Cmd instance with each installed CommandSet.
Diffstat (limited to 'cmd2/command_definition.py')
-rw-r--r-- | cmd2/command_definition.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/cmd2/command_definition.py b/cmd2/command_definition.py index 654043c8..a63e0efc 100644 --- a/cmd2/command_definition.py +++ b/cmd2/command_definition.py @@ -3,6 +3,8 @@ Supports the definition of commands in separate classes to be composed into cmd2.Cmd """ from typing import ( + Dict, + Mapping, Optional, Type, ) @@ -14,6 +16,9 @@ from .constants import ( from .exceptions import ( CommandSetRegistrationError, ) +from .utils import ( + Settable, +) # Allows IDEs to resolve types without impacting imports at runtime, breaking circular dependency issues try: # pragma: no cover @@ -90,6 +95,8 @@ class CommandSet(object): def __init__(self): self._cmd: Optional[cmd2.Cmd] = None + self._settables: Dict[str, Settable] = {} + self._settable_prefix = self.__class__.__name__ def on_register(self, cmd) -> None: """ @@ -126,3 +133,36 @@ class CommandSet(object): Subclasses can override this to perform remaining cleanup steps. """ self._cmd = None + + @property + def settable_prefix(self) -> str: + return self._settable_prefix + + @property + def settables(self) -> Mapping[str, Settable]: + return self._settables + + def add_settable(self, settable: Settable) -> None: + """ + Convenience method to add a settable parameter to the CommandSet + + :param settable: Settable object being added + """ + if self._cmd and not self._cmd.always_prefix_settables: + if settable.name in self._cmd.settables.keys() and settable.name not in self._settables.keys(): + raise KeyError(f'Duplicate settable: {settable.name}') + if settable.settable_obj is None: + settable.settable_obj = self + self._settables[settable.name] = settable + + def remove_settable(self, name: str) -> None: + """ + Convenience method for removing a settable parameter from the CommandSet + + :param name: name of the settable being removed + :raises: KeyError if the Settable matches this name + """ + try: + del self._settables[name] + except KeyError: + raise KeyError(name + " is not a settable parameter") |