我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getdoc()。
def __call__(self, parent_class, meth): key = (parent_class, meth.__name__) if key not in self.memoized: parent_module = self.get_parent_module(parent_class) module_tags = getattr(parent_module, '__tags__', []) class_tags = getattr(parent_class, '__tags__', []) tags = TAGS_RE.search(inspect.getdoc(meth) or '') if tags: test_tags = [t.strip() for t in tags.group(1).split(',')] else: test_tags = [] combined = set() for tags in (module_tags, class_tags, test_tags): if not tags: continue add = set([t for t in tags if not t.startswith('-')]) remove = set([t[1:] for t in tags if t not in add]) if add: combined.update(add) if remove: combined.difference_update(remove) self.memoized[key] = combined return self.memoized[key]
def analyse_action(func): """Analyse a function.""" description = inspect.getdoc(func) or 'undocumented action' arguments = [] args, varargs, kwargs, defaults = inspect.getargspec(func) if varargs or kwargs: raise TypeError('variable length arguments for action not allowed.') if len(args) != len(defaults or ()): raise TypeError('not all arguments have proper definitions') for idx, (arg, definition) in enumerate(zip(args, defaults or ())): if arg.startswith('_'): raise TypeError('arguments may not start with an underscore') if not isinstance(definition, tuple): shortcut = None default = definition else: shortcut, default = definition argument_type = argument_types[type(default)] if isinstance(default, bool) and default is True: arg = 'no-' + arg arguments.append((arg.replace('_', '-'), shortcut, default, argument_type)) return func, description, arguments
def _make_command(f, name, attrs, cls): if isinstance(f, Command): raise TypeError('Attempted to convert a callback into a ' 'command twice.') try: params = f.__click_params__ params.reverse() del f.__click_params__ except AttributeError: params = [] help = attrs.get('help') if help is None: help = inspect.getdoc(f) if isinstance(help, bytes): help = help.decode('utf-8') else: help = inspect.cleandoc(help) attrs['help'] = help _check_for_unicode_literals() return cls(name=name or f.__name__.lower(), callback=f, params=params, **attrs)
def modulesInPackage(self, packageName, package): docless = [] directory = path.dirname(package.__file__) for modfile in glob.glob(path.join(directory, '*.py')): moduleName = inspect.getmodulename(modfile) if moduleName == '__init__': # These are tested by test_packages. continue elif moduleName in ('spelunk_gnome','gtkmanhole'): # argh special case pygtk evil argh. How does epydoc deal # with this? continue try: module = reflect.namedModule('.'.join([packageName, moduleName])) except Exception, e: # print moduleName, "misbehaved:", e pass else: if not inspect.getdoc(module): docless.append(modfile) return docless
def testPackages(self): """Looking for docstrings in all packages.""" docless = [] for packageName in self.packageNames: try: package = reflect.namedModule(packageName) except Exception, e: # This is testing doc coverage, not importability. # (Really, I don't want to deal with the fact that I don't # have pyserial installed.) # print e pass else: if not inspect.getdoc(package): docless.append(package.__file__.replace('.pyc','.py')) self.failIf(docless, "No docstrings for package files\n" "%s" % ('\n'.join(map(errorInFile, docless),))) # This test takes a while and doesn't come close to passing. :(
def analyse_action(func): """Analyse a function.""" _deprecated() description = inspect.getdoc(func) or 'undocumented action' arguments = [] args, varargs, kwargs, defaults = inspect.getargspec(func) if varargs or kwargs: raise TypeError('variable length arguments for action not allowed.') if len(args) != len(defaults or ()): raise TypeError('not all arguments have proper definitions') for idx, (arg, definition) in enumerate(zip(args, defaults or ())): if arg.startswith('_'): raise TypeError('arguments may not start with an underscore') if not isinstance(definition, tuple): shortcut = None default = definition else: shortcut, default = definition argument_type = argument_types[type(default)] if isinstance(default, bool) and default is True: arg = 'no-' + arg arguments.append((arg.replace('_', '-'), shortcut, default, argument_type)) return func, description, arguments
def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError, e: signature = '%s()' % func_name self['Signature'] = signature
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config.get('show_class_members', True): if not self['Methods']: self['Methods'] = [(name, '', '') for name in sorted(self.methods)] if not self['Attributes']: self['Attributes'] = [(name, '', '') for name in sorted(self.properties)]
def handle_method(method, method_name, class_name): method_errors = [] # Skip out-of-library inherited methods module = inspect.getmodule(method) if module is not None: if not module.__name__.startswith('pylearn2'): return method_errors docstring = inspect.getdoc(method) if docstring is None: method_errors.append((class_name, method_name, '**missing** method-level docstring')) else: method_errors = [ (class_name, method_name, e) for e in NumpyFunctionDocString(docstring, method).get_errors() ] return method_errors
def handle_class(val, class_name): cls_errors = [] docstring = inspect.getdoc(val) if docstring is None: cls_errors.append((class_name, '**missing** class-level docstring')) else: cls_errors = [ (e,) for e in NumpyClassDocString(docstring, class_name, val).get_errors() ] # Get public methods and parse their docstrings methods = dict(((name, func) for name, func in inspect.getmembers(val) if not name.startswith('_') and callable(func) and type(func) is not type)) for m_name, method in six.iteritems(methods): # skip error check if the method was inherited # from a parent class (which means it wasn't # defined in this source file) if inspect.getmodule(method) is not None: continue cls_errors.extend(handle_method(method, m_name, class_name)) return cls_errors
def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*', '\*') signature = '%s%s' % (func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config=None): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config is not None and config.get('show_class_members', True): if not self['Methods']: self['Methods'] = [(name, '', '') for name in sorted(self.methods)] if not self['Attributes']: self['Attributes'] = [(name, '', '') for name in sorted(self.properties)]
def document_custom_method(section, method_name, method): """Documents a non-data driven method :param section: The section to write the documentation to. :param method_name: The name of the method :param method: The handle to the method being documented """ document_custom_signature( section, method_name, method) method_intro_section = section.add_new_section('method-intro') method_intro_section.writeln('') doc_string = inspect.getdoc(method) if doc_string is not None: method_intro_section.style.write_py_doc_string(doc_string)
def get_func_doc(name, func): doc_source = '' if name in SKIP: return '' if name[0] == '_': return '' if func in classes_and_functions: return '' classes_and_functions.add(func) header = name + inspect.formatargspec(*inspect.getargspec(func)) docstring = format_func_doc(inspect.getdoc(func), module_name + '.' + header) if docstring != '': doc_source += docstring doc_source += '\n\n ---------- \n\n' return doc_source
def get_method_doc(name, func): doc_source = '' if name in SKIP: return '' if name[0] == '_': return '' if func in classes_and_functions: return '' classes_and_functions.add(func) header = name + inspect.formatargspec(*inspect.getargspec(func)) docstring = format_method_doc(inspect.getdoc(func), header) if docstring != '': doc_source += '\n\n <span class="hr_large"></span> \n\n' doc_source += docstring return doc_source
def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature if sys.version_info[0] >= 3: argspec = inspect.getfullargspec(func) else: argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*', '\*') signature = '%s%s' % (func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature
def test(self): # in this example, put your test_plugin/test.html template at airflow/plugins/templates/test_plugin/test.htm attributes = [] data_table = [] operator_data={} for classes in ALL: operator_data['name']=str(classes.__name__) operator_data['type']=str(inspect.getfile(classes).split("_")[-1].split(".")[0]) operator_data['module']=str(inspect.getfile(classes).split("_")[-2]) try: operator_data['args']=str(classes.arguments) if classes.arguments else "NA" except Exception: operator_data['args']= "NOT FOUND" operator_data['desc']=str(inspect.getdoc(classes)) operator_data['loc']=str(inspect.getfile(classes)) data_table.append(copy.deepcopy(operator_data)) #data_table = json.dumps(data_table) return self.render("tac_plugin/tac.html",attributes=attributes,data_table=data_table)
def macros(macro, environ, data, *args, **kwargs): """Display a list of available macros and their documentation. **Arguments:** //No Arguments// **Example(s):** {{{ <<macros>> }}} You're looking at it! :) """ macros = environ.macros.items() s = "\n".join(["== %s ==\n%s\n" % (k, getdoc(v)) for k, v in macros]) return environ.parser.generate(s, environ=(environ, data))
def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature if sys.version_info[0] >= 3: argspec = inspect.getfullargspec(func) else: argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature
def params_from_doc(func): '''This function extracts the docstring from the specified function, parses it as a YAML document, and returns parameters for the os_server module.''' doc = inspect.getdoc(func) cfg = yaml.load(doc) for task in cfg: for module, params in task.items(): for k, v in params.items(): if k in ['nics'] and type(v) == str: params[k] = [v] task[module] = collections.defaultdict(str, params) return cfg[0]['os_server']
def doc_tag_line(f, func): '''what to show when func infos are shown while completing''' # that will be later shown in completions, w/o linesep possibilities # -> do the full infos (for ?<tab>) in s.doc # trying to get to a summary doc = (getdoc(func) or '').strip() doc = doc.split('\n', f.max_doc_lines)[:f.max_doc_lines] d = '' for i in range(len(doc)): if not doc[i]: return d.strip() d += '\n' + doc[i] if d[-1] in '!.': return d.strip() d = d.strip() return d if i < f.max_doc_lines else d + '(...)'