Skip to content

Added support for 'func' being a classmethod, with the 'klass' option. #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ The `module`, `func` and `prog` options are required.

`func` is a function that returns an instance of the `argparse.ArgumentParser` class.

If `func` is a class method then use `klass` to indicate the class it belongs to.

Alternatively, one can use :ref: like this::

.. argparse::
Expand Down
13 changes: 12 additions & 1 deletion sphinxarg/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def ensureUniqueIDs(items):

class ArgParseDirective(Directive):
has_content = True
option_spec = dict(module=unchanged, func=unchanged, ref=unchanged,
option_spec = dict(module=unchanged, func=unchanged, klass=unchanged, ref=unchanged,
prog=unchanged, path=unchanged, nodefault=flag,
nodefaultconst=flag, filename=unchanged,
manpage=unchanged, nosubcommands=unchanged, passparser=flag,
Expand Down Expand Up @@ -419,6 +419,8 @@ def run(self):
if 'module' in self.options and 'func' in self.options:
module_name = self.options['module']
attr_name = self.options['func']
if 'klass' in self.options:
klass_name = self.options['klass']
elif 'ref' in self.options:
_parts = self.options['ref'].split('.')
module_name = '.'.join(_parts[0:-1])
Expand All @@ -445,6 +447,15 @@ def run(self):
except:
raise self.error('Failed to import "%s" from "%s".\n%s' % (attr_name, module_name, sys.exc_info()[1]))

if 'klass' in self.options:
if not hasattr(mod, klass_name):
raise self.error((
'Module "%s" has no attribute "%s"\n'
'Incorrect argparse :module: or :klass: values?'
) % (module_name, klass_name))

mod = getattr(mod, klass_name)

if not hasattr(mod, attr_name):
raise self.error((
'Module "%s" has no attribute "%s"\n'
Expand Down