PageRenderTime 49ms CodeModel.GetById 39ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/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"""
12Utilities
13~~~~~~~~~
14"""
15import argparse
16import inspect
17
18from argh import compat
19
20
21def get_subparsers(parser, create=False):
22    """Returns the :class:`argparse._SubParsersAction` instance for given
23    :class:`ArgumentParser` instance as would have been returned by
24    :meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
25    it only works once and raises an exception on the second attempt, and the
26    public API seems to lack a method to get *existing* subparsers.
27
28    :param create:
29        If `True`, creates the subparser if it does not exist. Default if
30        `False`.
31
32    """
33    # note that ArgumentParser._subparsers is *not* what is returned by
34    # ArgumentParser.add_subparsers().
35    if parser._subparsers:
36        actions = [a for a in parser._actions
37                   if isinstance(a, argparse._SubParsersAction)]
38        assert len(actions) == 1
39        return actions[0]
40    else:
41        if create:
42            return parser.add_subparsers()
43
44
45def get_arg_names(function):
46    """Returns argument names for given function.  Omits special arguments
47    of instance methods (`self`) and static methods (usually `cls` or something
48    like this).
49    """
50    spec = compat.getargspec(function)
51    names = spec.args
52
53    if not names:
54        return []
55
56    if inspect.ismethod(function):
57        return names[1:]
58    else:
59        return names