summaryrefslogtreecommitdiff
path: root/cmd2/decorators.py
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2020-08-25 01:46:04 -0400
committerKevin Van Brunt <kmvanbrunt@gmail.com>2020-08-25 10:10:14 -0400
commit9b5a98825a9b00807a40494e8c634c392077ccd2 (patch)
treeb8cfbaca2ec4622a981d96c33c7a964ca621108e /cmd2/decorators.py
parenta540cfc5373cee2272de6c81be8b6fa8a78c6462 (diff)
downloadcmd2-git-9b5a98825a9b00807a40494e8c634c392077ccd2.tar.gz
Fixed RecursionError when printing an argparse.Namespace caused by custom attribute cmd2 was adding
Added get_statement() function to argparse.Namespace which returns __statement__ attribute
Diffstat (limited to 'cmd2/decorators.py')
-rw-r--r--cmd2/decorators.py14
1 files changed, 8 insertions, 6 deletions
diff --git a/cmd2/decorators.py b/cmd2/decorators.py
index 689f29c5..ccbbd832 100644
--- a/cmd2/decorators.py
+++ b/cmd2/decorators.py
@@ -1,7 +1,6 @@
# coding=utf-8
"""Decorators for ``cmd2`` commands"""
import argparse
-import types
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
from . import constants
@@ -190,6 +189,7 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
of unknown argument strings. A member called ``__statement__`` is added to the
``Namespace`` to provide command functions access to the :class:`cmd2.Statement`
object. This can be useful if the command function needs to know the command line.
+ ``__statement__`` can also be retrieved by calling ``get_statement()`` on the ``Namespace``.
:Example:
@@ -228,6 +228,7 @@ def with_argparser(parser: argparse.ArgumentParser, *,
:return: function that gets passed the argparse-parsed args in a Namespace
A member called __statement__ is added to the Namespace to provide command functions access to the
Statement object. This can be useful if the command function needs to know the command line.
+ ``__statement__`` can also be retrieved by calling ``get_statement()`` on the ``Namespace``.
:Example:
@@ -297,12 +298,13 @@ def with_argparser(parser: argparse.ArgumentParser, *,
except SystemExit:
raise Cmd2ArgparseError
else:
- setattr(ns, '__statement__', statement)
+ # Add statement to Namespace and a getter function for it
+ setattr(ns, constants.NS_ATTR_STATEMENT, statement)
+ setattr(ns, 'get_statement', lambda: statement)
- def get_handler(ns_self: argparse.Namespace) -> Optional[Callable]:
- return getattr(ns_self, constants.SUBCMD_HANDLER, None)
-
- setattr(ns, 'get_handler', types.MethodType(get_handler, ns))
+ # Add getter function for subcmd handler, which can be None
+ subcmd_handler = getattr(ns, constants.NS_ATTR_SUBCMD_HANDLER, None)
+ setattr(ns, 'get_handler', lambda: subcmd_handler)
args_list = _arg_swap(args, statement, *new_args)
return func(*args_list, **kwargs)