|
1 | 1 | # coding=utf-8
|
2 | 2 | """Decorators for ``cmd2`` commands"""
|
3 | 3 | import argparse
|
4 |
| -import types |
5 | 4 | from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
|
6 | 5 |
|
7 | 6 | from . import constants
|
@@ -190,6 +189,7 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
|
190 | 189 | of unknown argument strings. A member called ``__statement__`` is added to the
|
191 | 190 | ``Namespace`` to provide command functions access to the :class:`cmd2.Statement`
|
192 | 191 | object. This can be useful if the command function needs to know the command line.
|
| 192 | + ``__statement__`` can also be retrieved by calling ``get_statement()`` on the ``Namespace``. |
193 | 193 |
|
194 | 194 | :Example:
|
195 | 195 |
|
@@ -228,6 +228,7 @@ def with_argparser(parser: argparse.ArgumentParser, *,
|
228 | 228 | :return: function that gets passed the argparse-parsed args in a Namespace
|
229 | 229 | A member called __statement__ is added to the Namespace to provide command functions access to the
|
230 | 230 | Statement object. This can be useful if the command function needs to know the command line.
|
| 231 | + ``__statement__`` can also be retrieved by calling ``get_statement()`` on the ``Namespace``. |
231 | 232 |
|
232 | 233 | :Example:
|
233 | 234 |
|
@@ -297,12 +298,13 @@ def cmd_wrapper(*args: Any, **kwargs: Dict[str, Any]) -> Optional[bool]:
|
297 | 298 | except SystemExit:
|
298 | 299 | raise Cmd2ArgparseError
|
299 | 300 | else:
|
300 |
| - setattr(ns, '__statement__', statement) |
| 301 | + # Add statement to Namespace and a getter function for it |
| 302 | + setattr(ns, constants.NS_ATTR_STATEMENT, statement) |
| 303 | + setattr(ns, 'get_statement', lambda: statement) |
301 | 304 |
|
302 |
| - def get_handler(ns_self: argparse.Namespace) -> Optional[Callable]: |
303 |
| - return getattr(ns_self, constants.SUBCMD_HANDLER, None) |
304 |
| - |
305 |
| - setattr(ns, 'get_handler', types.MethodType(get_handler, ns)) |
| 305 | + # Add getter function for subcmd handler, which can be None |
| 306 | + subcmd_handler = getattr(ns, constants.NS_ATTR_SUBCMD_HANDLER, None) |
| 307 | + setattr(ns, 'get_handler', lambda: subcmd_handler) |
306 | 308 |
|
307 | 309 | args_list = _arg_swap(args, statement, *new_args)
|
308 | 310 | return func(*args_list, **kwargs)
|
|
0 commit comments