Skip to content

Commit 7796d28

Browse files
committed
support reading Argparse instances inside classes
So far, shphinxarg only has support for reading/importing Argparse instances from global variables/attributes within a module. However, there are use cases where Argparse is used inside classes of a module, not as a global variable. This is particularly the case for uses of 'argparse' in the context of CLI / REPL style user interfaces, such as for example those built using the 'cmd2' module. This change introduces the ability to specify :func: wit '.' notation like foo.bar.baz
1 parent f60fd4d commit 7796d28

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

sphinxarg/ext.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -471,14 +471,18 @@ def run(self):
471471

472472
# Skip this if we're dealing with a local file, since it obviously can't be imported
473473
if 'filename' not in self.options:
474+
_elements = attr_name.split('.')
474475
try:
475-
mod = __import__(module_name, globals(), locals(), [attr_name])
476+
mod = __import__(module_name, globals(), locals(), [_elements[0]])
476477
except ImportError:
477-
raise self.error(f'Failed to import "{attr_name}" from "{module_name}".\n{sys.exc_info()[1]}')
478-
479-
if not hasattr(mod, attr_name):
480-
raise self.error(('Module "%s" has no attribute "%s"\nIncorrect argparse :module: or :func: values?') % (module_name, attr_name))
481-
func = getattr(mod, attr_name)
478+
raise self.error(f'Failed to import "{_elements[0]}" from "{module_name}".\n{sys.exc_info()[1]}')
479+
obj = mod
480+
for i in _elements:
481+
if not hasattr(obj, i):
482+
raise self.error(f'"{obj}" has no attribute "{i}"\n'
483+
'Incorrect argparse :module: or :func: values?')
484+
obj = getattr(obj, i)
485+
func = obj
482486

483487
if isinstance(func, ArgumentParser):
484488
parser = func

0 commit comments

Comments
 (0)