/argh/utils.py

https://bitbucket.org/neithere/argh/ · Python · 59 lines · 21 code · 7 blank · 31 comment · 8 complexity · 03510822281f054cd1b33d16566c4225 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (c) 2010—2013 Andrey Mikhaylenko and contributors
  4. #
  5. # This file is part of Argh.
  6. #
  7. # Argh is free software under terms of the GNU Lesser
  8. # General Public License version 3 (LGPLv3) as published by the Free
  9. # Software Foundation. See the file README for copying conditions.
  10. #
  11. """
  12. Utilities
  13. ~~~~~~~~~
  14. """
  15. import argparse
  16. import inspect
  17. from argh import compat
  18. def get_subparsers(parser, create=False):
  19. """Returns the :class:`argparse._SubParsersAction` instance for given
  20. :class:`ArgumentParser` instance as would have been returned by
  21. :meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
  22. it only works once and raises an exception on the second attempt, and the
  23. public API seems to lack a method to get *existing* subparsers.
  24. :param create:
  25. If `True`, creates the subparser if it does not exist. Default if
  26. `False`.
  27. """
  28. # note that ArgumentParser._subparsers is *not* what is returned by
  29. # ArgumentParser.add_subparsers().
  30. if parser._subparsers:
  31. actions = [a for a in parser._actions
  32. if isinstance(a, argparse._SubParsersAction)]
  33. assert len(actions) == 1
  34. return actions[0]
  35. else:
  36. if create:
  37. return parser.add_subparsers()
  38. def get_arg_names(function):
  39. """Returns argument names for given function. Omits special arguments
  40. of instance methods (`self`) and static methods (usually `cls` or something
  41. like this).
  42. """
  43. spec = compat.getargspec(function)
  44. names = spec.args
  45. if not names:
  46. return []
  47. if inspect.ismethod(function):
  48. return names[1:]
  49. else:
  50. return names