From 7796d28597c0b612fafeab58929e0c6f817ed1dc Mon Sep 17 00:00:00 2001 From: Harald Welte Date: Sun, 4 Apr 2021 11:47:48 +0200 Subject: [PATCH] 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 --- sphinxarg/ext.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/sphinxarg/ext.py b/sphinxarg/ext.py index 384242a9..bcaeb605 100644 --- a/sphinxarg/ext.py +++ b/sphinxarg/ext.py @@ -471,14 +471,18 @@ def run(self): # Skip this if we're dealing with a local file, since it obviously can't be imported if 'filename' not in self.options: + _elements = attr_name.split('.') try: - mod = __import__(module_name, globals(), locals(), [attr_name]) + mod = __import__(module_name, globals(), locals(), [_elements[0]]) except ImportError: - raise self.error(f'Failed to import "{attr_name}" from "{module_name}".\n{sys.exc_info()[1]}') - - if not hasattr(mod, attr_name): - raise self.error(('Module "%s" has no attribute "%s"\nIncorrect argparse :module: or :func: values?') % (module_name, attr_name)) - func = getattr(mod, attr_name) + raise self.error(f'Failed to import "{_elements[0]}" from "{module_name}".\n{sys.exc_info()[1]}') + obj = mod + for i in _elements: + if not hasattr(obj, i): + raise self.error(f'"{obj}" has no attribute "{i}"\n' + 'Incorrect argparse :module: or :func: values?') + obj = getattr(obj, i) + func = obj if isinstance(func, ArgumentParser): parser = func