def _get_classes(object, all_=None): for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all_ is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all_, object): yield (key, value)
def __get_module_data(module) -> list: all_things = getattr(module, '__all__', None) data = [] for key, value in inspect.getmembers(module, pydoc.isdata): if pydoc.visiblename(key, all_things, module): data.append((key, value)) return data
def _get_funcs(object, all_=None): for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all_ is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all_, object): yield (key, value)
def process_class_using_instance(rootElt, obj, name, callables): doc = getsdoc(obj) or None classElt = SubElement(rootElt, "scope", ilk="class", name=name) if doc: classElt.set('doc', doc) callables[name] = classElt classElt.set('attributes', '__hidden__') for key, value in sorted(inspect.getmembers(obj)): if not visiblename(key): continue if inspect.isbuiltin(value): process_routine(classElt, value, key, callables) elif (_gIsPy3 and hasattr(value, 'class')) or ( not _gIsPy3 and isinstance(value, types.InstanceType)): klass = value.__class__ if klass.__module__ == name: t = klass.__name__ else: t = "%s.%s" % (klass.__module__, klass.__name__) varElt = SubElement(classElt, "variable", name=key, citdl=t) elif isdata(value): varElt = SubElement(classElt, "variable", name=key, citdl=type(value).__name__)
def analyze_module(self, obj): try: _all = obj.__all__ except AttributeError: _all = None classes = [] for key, value in inspect.getmembers(obj, inspect.isclass): if (_all is not None or (inspect.getmodule(value) or obj) is obj): if pydoc.visiblename(key, _all, obj): classes.append(value) funcs = [] for key, value in inspect.getmembers(obj, inspect.isroutine): if (_all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is obj): if pydoc.visiblename(key, _all, obj): funcs.append(value) return classes, funcs
def __get_module_functions(module) -> list: all_things = getattr(module, '__all__', None) functions = [] for key, value in inspect.getmembers(module, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if all_things is not None or inspect.isbuiltin( value) or inspect.getmodule(value) is module: if pydoc.visiblename(key, all_things, module): functions.append((key, value)) return functions
def __get_module_classes(module) -> list: all_things = getattr(module, '__all__', None) classes = [] for key, value in inspect.getmembers(module, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if all_things is not None or (inspect.getmodule(value) or module) is module: if pydoc.visiblename(key, all_things, module): classes.append((key, value)) return classes
def _is_child(self, obj: object) -> bool: is_child = inspect.isclass(obj) | inspect.isfunction(obj) is_child &= inspect.getmodule(obj) is self.obj try: is_child &= not obj.__name__.startswith("_") is_child &= pydoc.visiblename(obj.__name__) is_child |= obj.__name__ in self.includes is_child &= obj.__name__ not in self.excludes except AttributeError: is_child = False return is_child
def get_funcs(thing): """ return functions in python file """ funcs = [] _object, _ = pydoc.resolve(thing) _all = getattr(_object, '__all__', None) for key, value in inspect.getmembers(_object, inspect.isroutine): if _all is not None or inspect.isbuiltin( value) or inspect.getmodule(value) is _object: if pydoc.visiblename(key, _all, _object): funcs.append((key, value)) return funcs
def getclasses(module): try: module = locate(module) except ErrorDuringImport: return [] all = getattr(module, '__all__', None) classes = [] for key, value in inspect.getmembers(module, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or module) is module): if visiblename(key, all, module): classes.append((key, value)) return classes
def should_document_module_member(name, thing, module): if not pydoc.visiblename(name, getattr(module, "__all__", None), thing): return False if hasattr(module, "__all__"): return True if isinstance(thing, types.ModuleType): return False if hasattr(thing, "__module__") and thing.__module__ != module.__name__: return False # Skip aliases for now. Might want to document aliases specially in the # future. if hasattr(thing, "__name__") and thing.__name__ != name: return False return True
def get_funcs(module): """ Acquire functions in python file. :param module: python module. :return: dict in python module. """ funcs = {} _object, _ = pydoc.resolve(module) _all = getattr(_object, '__all__', None) for key, value in inspect.getmembers(_object, inspect.isroutine): if _all is not None or inspect.isbuiltin( value) or inspect.getmodule(value) is _object: if pydoc.visiblename(key, _all, _object): funcs[key] = value return funcs
def get_funcs(thing): """ Acquire functions in python file. :param thing: python module. :return: list(function name, function object), function name and corresponding function object in python module. """ funcs = [] _object, _ = pydoc.resolve(thing) _all = getattr(_object, '__all__', None) for key, value in inspect.getmembers(_object, inspect.isroutine): if _all is not None or inspect.isbuiltin( value) or inspect.getmodule(value) is _object: if pydoc.visiblename(key, _all, _object): funcs.append((key, value)) return funcs
def process_class_using_instance(rootElt, obj, name, callables): doc = getsdoc(obj) or None classElt = SubElement(rootElt, "scope", ilk="class", name=name) if doc: classElt.set('doc', doc) callables[name] = classElt classElt.set('attributes', '__hidden__') for key, value in sorted(inspect.getmembers(obj)): if not visiblename(key): continue if inspect.isbuiltin(value): process_routine(classElt, value, key, callables) elif (_gIsPy3 and hasattr(value, 'class')) or (not _gIsPy3 and isinstance(value, types.InstanceType)): klass = value.__class__ if klass.__module__ == name: t = klass.__name__ else: t = "%s.%s" % (klass.__module__, klass.__name__) varElt = SubElement(classElt, "variable", name=key, citdl=t) elif isdata(value): varElt = SubElement(classElt, "variable", name=key, citdl=type(value).__name__)
def docmodule(self, object, name=None, mod=None): """Produce Markdown documentation for a given module object.""" try: all = object.__all__ except AttributeError: all = None name = object.__name__ # ignore the passed-in name synop, desc = pydoc.splitdoc(pydoc.getdoc(object)) synop = synop if synop else name result = self.header(synop, self.hlevel, name, 'module') if desc: result = result + desc.rstrip() + '\n\n' docloc = self.getdocloc(object) if docloc is not None: result = result + 'Module Documentation: <%s>\n\n' % docloc classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if pydoc.visiblename(key, all, object): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if pydoc.visiblename(key, all, object): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, pydoc.isdata): if pydoc.visiblename(key, all, object): data.append((key, value)) self.hlevel += 2 #modpkgs = [] #modpkgs_names = set() #if hasattr(object, '__path__'): # for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): # modpkgs_names.add(modname) # if ispkg: # modpkgs.append(modname + ' (package)') # else: # modpkgs.append(modname) # # modpkgs.sort() # result = result + self.section( # 'PACKAGE CONTENTS', '\n'.join(modpkgs)) # ## Detect submodules as sometimes created by C extensions #submodules = [] #for key, value in inspect.getmembers(object, inspect.ismodule): # if value.__name__.startswith(name + '.') and key not in modpkgs_names: # submodules.append(key) #if submodules: # submodules.sort() # result = result + self.section( # 'SUBMODULES', '\n'.join(submodules)) if classes: classlist = map(lambda key_value: key_value[1], classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name) ] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', '\n'.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', '\n'.join(contents)) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', '\n'.join(contents)) if hasattr(object, '__version__') and not inspect.ismodule(object.__version__): version = object.__version__ if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', object.__date__) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', object.__author__) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', object.__credits__) self.hlevel -= 2 return result
def docclass(self, object, name=None, mod=None, *ignored): """Produce Markdown documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return pydoc.classname(c, m) if name == realname: title = 'class ' + realname else: title = name + ' = class ' + realname if bases: parents = map(makename, bases) title = title + '(%s)' % ', '.join(parents) title = self.header(title, self.hlevel, name, 'class') self.hlevel += 1 doc = pydoc.getdoc(object) contents = doc and [doc + '\n'] or [] push = contents.append # List the mro, if non-trivial. mro = pydoc.deque(inspect.getmro(object)) if len(mro) > 2: push("Method resolution order:\n") for base in mro: push('* ' + makename(base)) push('') # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('-' * 70 + '\n') self.needone = 1 hr = HorizontalRule() def spill(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) push(self._docdescriptor(name, value, mod)) else: push(self.document(value, name, mod, object)) return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)): doc = pydoc.getdoc(value) else: doc = None push( self.docother(getattr(object, name), name, mod, maxlen=70, doc=doc) + '\n') return attrs attrs = filter(lambda data: pydoc.visiblename(data[0], obj=object), pydoc.classify_class_attrs(object)) while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = pydoc._split_list(attrs, lambda t: t[2] is thisclass) if thisclass is pydoc.__builtin__.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % pydoc.classname( thisclass, object.__module__) # Sort attrs by name. attrs.sort() # Pump out the attrs, segregated by kind. attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited self.hlevel -= 1 contents = '\n'.join(contents) if not contents: return title return title + contents.rstrip() + '\n'
def docmodule(modname, root, force=False, usefile=False, dir=None): name = modname modulename = modname if modname == '*': if _gIsPy3: modname = 'builtins' else: modname = '__builtin__' if dir: modinfo = imp.find_module(modname, [dir]) try: obj = imp.load_module(modname, *modinfo) except ImportError: ex = sys.exc_info()[1] cixfile = SubElement(root, "file", lang="Python", mtime=str(int(time.time())), path=os.path.basename(modinfo[1]), error=str(ex)) return else: # no dir is given, try to load from python path try: obj, modulename = pydoc.resolve(modname) except Exception: print(sys.exc_info()[1]) return result = '' try: all = obj.__all__ except AttributeError: all = None try: filename = inspect.getabsfile(obj) except TypeError: filename = '(built-in)' if usefile: cixfile = SubElement(root, "file", lang="Python", mtime=str(int(time.time())), path=os.path.basename(filename)) else: cixfile = root module = obj doc = getsdoc(obj) or None moduleElt = SubElement(cixfile, "scope", ilk="blob", name=name, lang="Python") if doc: moduleElt.set('doc', doc) skips = module_skips.get(name, []) callables = {} for key, value in sorted(inspect.getmembers(obj)): if key in skips: continue if inspect.ismodule(value): process_module(moduleElt, value, key, callables, modname) continue if not visiblename(key): # forget about __all__ continue if (inspect.isfunction(value) or inspect.ismethod(value) or inspect.ismethoddescriptor(value) or inspect.isroutine(value) or inspect.isbuiltin(value)): process_routine(moduleElt, value, key, callables) elif inspect.isclass(value) or (not _gIsPy3 and isinstance(value, types.TypeType)): process_class(moduleElt, value, key, callables) elif (_gIsPy3 and hasattr(value, 'class')) or (not _gIsPy3 and isinstance(value, types.InstanceType)): klass = value.__class__ if klass.__module__ == name: t = klass.__name__ else: t = "%s.%s" % (klass.__module__, klass.__name__) varElt = SubElement(moduleElt, "variable", name=key, citdl=t) # make sure we also process the type of instances process_class(moduleElt, klass, klass.__name__, callables) elif isdata(value): varElt = SubElement(moduleElt, "variable", name=key, citdl=type(value).__name__) else: log.warn("unexpected element in module '%s': '%s' is %r", modulename, name, type(value)) helpername = os.path.join("helpers", modname + '_helper.py') namespace = {} if os.path.exists(helpername): sys.stderr.write("Found helper module: %r\n" % helpername) if _gIsPy3: exec(compile(open(helpername).read(), os.path.basename(helpername), 'exec'), namespace, namespace) else: execfile(helpername, namespace, namespace) # look in helpername for analyze_retval_exprs, which is a list of (callable_string, *args) # and which corresponds to callables which when called w/ the specified args, will return # variables which should be used to specify the <return> subelement of the callable. analyze_retval_exprs = namespace.get('analyze_retval_exprs', []) signatures = namespace.get('signatures', {}) for retval_expr in analyze_retval_exprs: name, args = retval_expr if name in callables: callableElt = callables[name] if name in signatures: sig = signatures[name] callableElt.set('signature', sig) # XXX??? playarea = module.__dict__ var = eval(name, playarea)(*args) # find out what type that is callableElt.set("returns", type(var).__name__) else: print("Don't know about: %r" % expr) hidden_classes_exprs = namespace.get('hidden_classes_exprs', []) for expr in hidden_classes_exprs: playarea = module.__dict__ var = eval(expr, playarea) name = type(var).__name__ process_class_using_instance(moduleElt, var, name, callables) function_overrides = namespace.get('function_overrides') if function_overrides is not None: for name in function_overrides: namesplit = name.split(".") callableElt = callables[namesplit[0]] for subname in namesplit[1:]: for childElt in callableElt: if childElt.get("name") == subname: callableElt = childElt break else: callableElt = None break if callableElt is None: print(" couldn't find elem with name: %r" % (name, )) continue overrides = function_overrides[name] for setting, value in overrides.items(): print(" overriding %s.%s %s attribute from %r to %r" % (modname, name, setting, callableElt.get(setting), value)) callableElt.set(setting, value)
def _get_data(object, all_=None): for key, value in inspect.getmembers(object, isdata): if visiblename(key, all_, object): yield (key, value)
def docclass(self, object, name=None, mod=None): """Produce text documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return pydoc.classname(c, m) if name == realname: title = '== class ' + self.bold(realname) else: title = '== ' + self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) title += '(%s)' % join(parents, ', ') title += " ==" classDoc = pydoc.getdoc(object) contents = [] if classDoc: itrs = [] for k in classDoc.split('\n'): if "@ivar " in k: n = k.strip('@ivar ').split(':') itrs.append(" * '''%s''': %s" % tuple(n)) else: itrs.append(k) contents.append('\n'.join(itrs) + '\n') push = contents.append # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: push("Method resolution order:") for base in mro: push(' ' + makename(base)) push('') def spill(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: push(msg) for name, kind, homecls, value in ok: push( self.document(getattr(object, name), name, mod, object)) return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = pydoc._split_list(attrs, predicate) if ok: push(msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = pydoc.getdoc(value) else: doc = None push( self.docother(getattr(object, name), name, mod, maxlen=70, doc=doc) + '\n') return attrs attrs = filter( lambda (name, kind, cls, value): pydoc.visiblename(name), inspect.classify_class_attrs(object)) while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = pydoc._split_list(attrs, lambda t: t[2] is thisclass) if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % pydoc.classname( thisclass, object.__module__) filter(lambda t: not t[0].startswith('_'), attrs) # Sort attrs by name. attrs.sort() # Pump out the attrs, segregated by kind. attrs = spill("=== Methods %s: ===\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("=== Class methods %s: ===\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("=== Static methods %s: ===\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors("=== Data descriptors %s: ===\n" % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata("=== Data and other attributes %s: ===\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = '\n'.join(contents) if not contents: return title + '\n' return title + '\n' + self.indent(rstrip(contents), '') + '\n'
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) # modified filelink = self.filelink(url, path) # end modified except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda (key, value), s=self: s.modulelink(value)) result = result + self.bigsection( 'Modules', '#fffff', '#aa55cc', contents) if classes: classlist = map(lambda (key, value): value, classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result
def docclass(self, object, name=None, mod=None, *ignored): """Produce text documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return classname(c, m) if name == realname: title = 'class ' + self.bold(realname) else: title = self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) title = title + '(%s)' % ', '.join(parents) title += ':' contents = [] push = contents.append doc = getdoc(object) if doc: push(f'"""\n{doc}\n"""') # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: push("\n## Method resolution order:") for i, base in enumerate(mro, 1): push(f'# {i}) ' + makename(base)) push('') # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('# ' + '-' * 68) self.needone = 1 hr = HorizontalRule() def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push('# ' + msg) for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) push(self._docdescriptor(name, value, mod)) else: push(self.document(value, name, mod, object)) return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push('# ' + msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push('# ' + msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None try: obj = getattr(object, name) except AttributeError: obj = homecls.__dict__[name] push( self.docother(obj, name, mod, maxlen=70, doc=doc) + '\n') return attrs attrs = [(name, kind, cls, value) for name, kind, cls, value in classify_class_attrs(object) if visiblename(name, obj=object)] while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is builtins.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % classname(thisclass, object.__module__) sort_attributes(attrs, object) # Pump out the attrs, segregated by kind. attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = '\n'.join(contents) or 'pass' return '\n' + title + '\n' + self.indent(contents.rstrip(), ' ') + '\n'
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML5 documentation for a module object.""" level = 1 # FIXME: use passed level in the future components = {} # where we're storing all components to be output name = object.__name__ # ignore the passed-in name. not passed in anyways? try: all = object.__all__ except AttributeError: all = None parts = name.split('.') links = [] for i in range(len(parts) - 1): links.append('<a href="%s">%s</a>' % (self.url('.'.join(parts[:i + 1])), parts[i])) head_link = '.'.join(links + parts[-1:]) try: path = inspect.getabsfile(object) if self.local: url = path if sys.platform == 'win32': # in case i want to give this to the python project import nturl2path url = nturl2path.pathname2url(path) components[ 'fileref'] = '<a class="file-reference" href="file:%s">%s</a>' % ( url, path) else: components[ 'fileref'] = '<span class="file-reference">%s</span>' % path except TypeError: components[ 'fileref'] = '<span class="file-reference builtin">(built-in)</span>' components['fileref'] = '' # TODO remove fileref info = [] if hasattr(object, '__version__'): version = pydoc._binstr(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(pydoc._binstr(object.__date__))) # build the main heading if info: components['head'] = self.heading( level + 1, '%s (<span class="info">%s)' % (head_link, ', '.join(info))) else: # heading which is a linked representation of the module "address" components['head'] = self.heading(level + 1, head_link) # get the official url of object, if any docloc = self.getdocloc(object) if docloc is not None: components[ 'docloc'] = '<a class="official-docs" href="%s" target="_blank" rel="noreferrer noopener">Module Docs</a>' % docloc else: components['docloc'] = '' # collect modules, classes, functions and data in `object` modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if pydoc.visiblename(key, all, object): classes.append((key, value)) cdict[key] = cdict[value] = '#' + \ key # key used as URL fragment for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = self.url( modname ) + '#' + key # key used as URL fragment funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if pydoc.visiblename(key, all, object): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, pydoc.isdata): if pydoc.visiblename(key, all, object): data.append((key, value)) # build documentation for the thing passed in components['doc'] = self.getdoc(object) if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules( object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() components['modules'] = self.heading( level + 2, 'Package Contents') + self.listing( modpkgs, formatter=self.modpkglink) elif modules: components['modules'] = self.heading( level + 2, 'Modules') + self.listing( [module for _, module in modules], formatter=self.modulelink) if classes: classlist = [cls for _, cls in classes] classtree = self.formattree(inspect.getclasstree(classlist, 1), name) classdocs = [] for key, value in classes: classdocs.append(self.document(value, key, name, fdict, cdict)) components['classes'] = self.heading(level + 2, 'Classes') components['classes'] += classtree components['classes'] += '<dl class="classes">' components['classes'] += '\n'.join(classdocs) components['classes'] += '</dl>' if funcs: docs = [] for key, value in funcs: docs.append(self.document(value, key, name, fdict, cdict)) components['funcs'] = self.heading(level + 2, 'Functions') components['funcs'] += '<dl class="functions">' components['funcs'] += '\n'.join(docs) components['funcs'] += '</dl>' if data: docs = [] for key, value in data: docs.append(self.document(value, key)) components['data'] = self.heading(level + 2, 'Data') components['data'] += '<dl class="data">' components['data'] += '\n'.join(docs) components['data'] += '</dl>' if hasattr(object, '__author__'): components['author'] = self.heading( level + 2, 'Author') + pydoc._binstr(object.__author__) if hasattr(object, '__credits__'): components['credits'] = self.geadubg( level + 2, 'Credits') + pydoc._binstr(object.__credits__) result = '%(head)s %(docloc)s' % components # result = '%(head)s %(fileref)s %(docloc)s' % components # TODO fileref disabled result += '<div class="module">' % components result += ' <div class="docstring">%(doc)s</div>' % components if 'modules' in components: result += ' <div class="modules">%(modules)s</div>' % components if 'classes' in components: result += ' <div class="classes">%(classes)s</div>' % components if 'funcs' in components: result += ' <div class="functions">%(funcs)s</div>' % components if 'author' in components: result += '<div class="author">%(author)s</div>' % components if 'credits' in components: result += '<div class="credits">%(credits)s</div>' % components result += '</div>' return result
import pydoc result = {'Function': [], 'Data': [], 'Class': {}} a = inspect.getmembers(timeit) b = inspect.getmodule(timeit) all = [i[0] for i in a] print(all) for i in a: current_obj = getattr(timeit, i[0]) if inspect.isclass(current_obj): class_func = [] c = inspect.getmembers(getattr(timeit, i[0])) for j in c: obj = getattr(getattr(timeit, i[0]), j[0]) if inspect.isfunction(obj): class_func.append(j[0]) result['Class'][i[0]] = class_func if inspect.isfunction(current_obj): result['Function'].append(i[0]) if not re.match('^<.*$>?', str(i[1])) or isinstance( i[1], (str, int, list, dict)): # 是 str 或 int 或 list 或 dict 实例就是 Data if pydoc.visiblename(i[0], all, object): result['Data'].append(i[0]) print(len(a)) print(result)
def docclass(self, cls, name=None, mod=None): """Produce text documentation for the class object cls.""" # the overall document, as a line-delimited list document = [] # get the object's actual name, defaulting to the passed in name name = name or cls.__name__ # get the object's bases bases = cls.__bases__ # get the object's module mod = cls.__module__ # get the object's MRO mro = [pydoc.classname(base, mod) for base in inspect.getmro(cls)] # get the object's classname, which should be printed classtitle = self.process_class_name(name, bases, mod) document.append(classtitle) document.append(self.underline) # get the object's docstring, which should be printed docstring = self.process_docstring(cls) document.append(docstring) # get all the attributes of the class attrs = [] for name, kind, classname, value in pydoc.classify_class_attrs(cls): if pydoc.visiblename(name): #if kind is not builtins.object: if classname == cls: obj = (name, kind, classname, value) attrs.append(obj) # sort them into categories data = [attr for attr in attrs if attr[1] == "data"] descriptors = [attr for attr in attrs if attr[1] == "data descriptor"] methods = [attr for attr in attrs if "method" in attr[1]] # start the data section document.append(self.process_subsection("data")) document.append(self.underline) # process your attributes for name, kind, classname, value in data: document.append(self.document(getattr(cls, name), name, mod, cls)) # start the descriptors section document.append(self.process_subsection("descriptors")) document.append(self.underline) # process your descriptors for desc in descriptors: document.append(self._docdescriptor(name, value, mod)) # start the methods section document.append(self.process_subsection("methods")) document.append(self.underline) # process your methods for f in methods: if not f[0].startswith("__"): document.append(self.docroutine(f[-1])) return "\n".join(document)
def __show_clazz_attribute(cls, clazz, name: str, clz) -> bool: specials = ['__init__'] return pydoc.visiblename(name, obj=clazz) and ( (name in specials and clz == clazz) or not name.startswith('__'))
def update_event(self, inp=-1): self.set_output_val( 0, pydoc.visiblename(self.input(0), self.input(1), self.input(2)))
def docclass(self, cls, name=None, mod=None): """Produce text documentation for the class object cls.""" # the overall document, as a line-delimited list document = [] # get the object's actual name, defaulting to the passed in name name = name or cls.__name__ # get the object's bases bases = cls.__bases__ # get the object's module mod = cls.__module__ # get the object's MRO mro = [pydoc.classname(base, mod) for base in inspect.getmro(cls)] # get the object's classname, which should be printed classtitle = self.process_class_name(name, bases, mod) document.append(classtitle) document.append(self.underline) # get the object's docstring, which should be printed docstring = self.process_docstring(cls) document.append(docstring) # get all the attributes of the class attrs = [] for name, kind, classname, value in pydoc.classify_class_attrs(cls): if pydoc.visiblename(name): attrs.append((name, kind, classname, value)) # sort them into categories data, descriptors, methods = [], [], [] for attr in attrs: if attr[1] == "data" and not attr[0].startswith("_"): data.append(attr) elif attr[1] == "data descriptor" and not attr[0].startswith("_"): descriptors.append(attr) elif "method" in attr[1] and not attr[2] is builtins.object: methods.append(attr) if data: # start the data section document.append(self.process_subsection(self.bold("data"))) document.append(self.underline) # process your attributes for name, kind, classname, value in data: if hasattr(value, '__call__') or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None document.append( self.docother( getattr(cls, name), name, mod, maxlen=70, doc=doc) + '\n') if descriptors: # start the descriptors section document.append(self.process_subsection(self.bold("descriptors"))) document.append(self.underline) # process your descriptors for name, kind, classname, value in descriptors: document.append(self._docdescriptor(name, value, mod)) if methods: # start the methods section document.append(self.process_subsection(self.bold("methods"))) document.append(self.underline) # process your methods for name, kind, classname, value in methods: document.append( self.document(getattr(cls, name), name, mod, cls)) return "\n".join(document)
def docclass(self, cls, name=None, mod=None): """Produce markdown documentation for the class obj cls.""" # the overall document, as a line-delimited list document = [] # get the obj's actual name, defaulting to the passed in name name = name or cls.__name__ # get the obj's bases bases = cls.__bases__ # get the obj's module mod = cls.__module__ # get the obj's classname, which should be printed classtitle = self.process_class_name(name, bases, mod) document.append(classtitle) # get the obj's docstring, which should be printed docstring = self.process_docstring(cls) document.append(self.process_subsection("description")) document.append(self.underline) document.append(docstring) # get all the attributes of the class attrs = [] for name, kind, classname, value in pydoc.classify_class_attrs(cls): if pydoc.visiblename(name): if kind is not __builtin__.object: if classname == cls: obj = (name, kind, classname, value) attrs.append(obj) # sort them into categories data = [attr for attr in attrs if attr[1] == "data"] descriptors = [attr for attr in attrs if attr[1] == "data descriptor"] methods = [attr for attr in attrs if "method" in attr[1]] # start the data section if data: document.append(self.process_subsection("data")) document.append(self.underline) # process your attributes for name, kind, classname, value in data: document.append(self.document(getattr(cls, name), name, mod, cls)) # start the descriptors section if descriptors: document.append(self.process_subsection("descriptors")) document.append(self.underline) # process your descriptors for _ in descriptors: document.append(self._docdescriptor(name, value, mod)) # start the methods section if methods: document.append(self.process_subsection("methods")) document.append(self.underline) # process your methods for f in methods: if not f[0].startswith("__"): document.append(self.docroutine(f[-1])) return "\n".join(document).replace('\n', '\n> ')
def docclass(self, cls, name=None, mod=None): """Produce text documentation for the class object cls.""" # the overall document, as a line-delimited list document = [] # get the object's actual name, defaulting to the passed in name name = name or cls.__name__ # get the object's bases bases = cls.__bases__ # get the object's module mod = cls.__module__ # get the object's MRO mro = [pydoc.classname(base, mod) for base in inspect.getmro(cls)] # get the object's classname, which should be printed classtitle = self.process_class_name(name, bases, mod) document.append(classtitle) document.append(self.underline) # get the object's docstring, which should be printed docstring = self.process_docstring(cls) document.append(docstring) # get all the attributes of the class attrs = [] for name, kind, classname, value in pydoc.classify_class_attrs(cls): if pydoc.visiblename(name): attrs.append((name, kind, classname, value)) # sort them into categories data, descriptors, methods = [], [], [] for attr in attrs: if attr[1] == "data" and not attr[0].startswith("_"): data.append(attr) elif attr[1] == "data descriptor" and not attr[0].startswith("_"): descriptors.append(attr) elif "method" in attr[1] and not attr[2] is builtins.object: methods.append(attr) if data: # start the data section document.append(self.process_subsection(self.bold("data"))) document.append(self.underline) # process your attributes for name, kind, classname, value in data: if hasattr(value, '__call__') or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None document.append(self.docother(getattr(cls, name), name, mod, maxlen=70, doc=doc) + '\n') if descriptors: # start the descriptors section document.append(self.process_subsection(self.bold("descriptors"))) document.append(self.underline) # process your descriptors for name, kind, classname, value in descriptors: document.append(self._docdescriptor(name, value, mod)) if methods: # start the methods section document.append(self.process_subsection(self.bold("methods"))) document.append(self.underline) # process your methods for name, kind, classname, value in methods: document.append(self.document(getattr(cls, name), name, mod, cls)) return "\n".join(document)
def docmodule(self, obj, name=None, mod=None): """Produce markdown documentation for a given module obj.""" name = obj.__name__ # ignore the passed-in name synop, desc = pydoc.splitdoc(pydoc.getdoc(obj)) result = self.section('NAME', name.replace(r'_', r'\_') + (synop and ' - ' + synop)) try: moduleall = obj.__all__ except AttributeError: moduleall = None try: filepath = os.path.dirname(inspect.getabsfile(obj)) except TypeError: filepath = '(built-in)' result = result + self.section('FILE', '`'+filepath+'`') docloc = self.getdocloc(obj) if docloc is not None: result = result + self.section('MODULE DOCS', docloc) if desc: result = result + self.section('DESCRIPTION', desc) if hasattr(obj, '__version__'): version = pydoc._binstr(obj.__version__) if version[:11] == '$Revision: ' and version[-1:] == '$': version = version[11:-1].strip() result = result + self.section('VERSION', version) if hasattr(obj, '__date__'): result = result + self.section('DATE', pydoc._binstr(obj.__date__)) if hasattr(obj, '__author__'): result = result + self.section('AUTHOR', pydoc._binstr(obj.__author__)) if hasattr(obj, '__credits__'): result = result + self.section('CREDITS', pydoc._binstr(obj.__credits__)) classes = [] for key, value in inspect.getmembers(obj, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if moduleall is not None or (inspect.getmodule(value) or obj) is obj: if pydoc.visiblename(key, moduleall, obj): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(obj, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if moduleall is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is obj: if pydoc.visiblename(key, moduleall, obj): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(obj, pydoc.isdata): if pydoc.visiblename(key, moduleall, obj): data.append((key, value)) modules = [] for key, _ in inspect.getmembers(obj, inspect.ismodule): modules.append(key) if modules: modules = sorted(modules) contents = ', '.join(['[%s](https://www.google.com/#q=python+%s)' % (m, m) for m in modules]) + '\n{: .lead}' result = result + self.section('MODULES', contents) modpkgs = [] modpkgs_names = set() if hasattr(obj, '__path__'): for _, modname, ispkg in pkgutil.iter_modules(obj.__path__): modpkgs_names.add(modname) if ispkg: modpkgs.append(modname + ' (package)') else: modpkgs.append(modname) modpkgs.sort() result = result + self.section('PACKAGE CONTENTS', pydoc.join(modpkgs, '\n')) # Detect submodules as sometimes created by C extensions submodules = [] for key, value in inspect.getmembers(obj, inspect.ismodule): if value.__name__.startswith(name + '.') and key not in modpkgs_names: submodules.append(key) if submodules: submodules.sort() result = result + self.section('SUBMODULES', pydoc.join(submodules, '\n')) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', pydoc.join(contents, '\n')) if classes: classlist = [x[1] for x in classes] contents = [self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', pydoc.join(contents, '\n')) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name)) result = result + self.section('DATA', pydoc.join(contents, '\n')) return result
def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ contents = [] push = contents.append # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('<hr>\n') self.needone = 1 hr = HorizontalRule() # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: hr.maybe() push('<dl><dt>Method resolution order:</dt>\n') for base in mro: push('<dd>%s</dd>\n' % self.classlink(base, object.__module__)) push('</dl>\n') def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure # in their __get__. # (bug aroberge/mod_pydoc#1785) push(self._docdescriptor(name, value, mod)) else: push( self.document(value, name, mod, funcs, classes, mdict, object)) push('\n') return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) if callable(value) or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None if doc is None: push('<dl><dt>%s</dt><dd></dd></dl>\n' % base) else: doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd><code>%s</code></dd>' % doc push('<dl><dt>%s%s</dt></dl>\n' % (base, doc)) push('\n') return attrs attrs = [(name, kind, cls, value) for name, kind, cls, value in classify_class_attrs(object) if visiblename(name, obj=object)] mdict = {} for key, kind, homecls, value in attrs: mdict[key] = anchor = '#' + name + '-' + key try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) pass try: # The value may not be hashable (e.g., a data attr with # a dict or list value). mdict[value] = anchor except TypeError: pass while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is builtins.object: attrs = inherited continue elif thisclass is object: tag = 'defined here' else: tag = 'inherited from %s' % self.classlink( thisclass, object.__module__) tag += ':<br>\n' # Sort attrs by name. attrs.sort(key=lambda t: t[0]) # Pump out the attrs, segregated by kind. attrs = spill('Methods %s' % tag, attrs, lambda t: t[1] == 'method') attrs = spill('Class methods %s' % tag, attrs, lambda t: t[1] == 'class method') attrs = spill('Static methods %s' % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors('Data descriptors %s' % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata('Data and other attributes %s' % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = ''.join(contents) if name == realname: title = '<span id="%s" class="signature"> class %s</span>' % ( name, realname) else: title = ( '%s = <span id="%s" class="signature">class %s</span>' % (name, name, realname)) if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % ', '.join(parents) doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '<code>%s<br> </code>' % doc return self.html_section(title, contents, 3, doc, css_class="docclass")
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = pydoc.splitdoc(pydoc.getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop)) try: all = object.__all__ except AttributeError: all = None try: file = "source:tums/trunk/source/%s" % inspect.getabsfile( object).split('/source/')[-1] except TypeError: file = '(built-in)' result = result + self.section('FILE', file) docloc = self.getdocloc(object) if docloc is not None: result = result + self.section('MODULE DOCS', docloc) if desc: result = result + self.section('DESCRIPTION', desc) classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if pydoc.visiblename(key, all): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if pydoc.visiblename(key, all): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, pydoc.isdata): if pydoc.visiblename(key, all): data.append((key, value)) if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules( object.__path__): if ispkg: modpkgs.append(modname + ' (package)') else: modpkgs.append(modname) modpkgs.sort() result = result + self.section('PACKAGE CONTENTS', join(modpkgs, '\n')) if classes: classlist = map(lambda (key, value): value, classes) contents = [] contentsFirst = [] for key, value in classes: thisDoc = self.document(value, key, name) if not "==" in thisDoc: contentsFirst.append(thisDoc) else: contents.append(thisDoc) result = result + self.section( 'CLASSES', join(contentsFirst, '\n\n') + "\n\n" + join(contents, '\n')) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', join(contents, '\n')) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', join(contents, '\n\n')) if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', str(object.__author__)) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', str(object.__credits__)) return result
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts) - 1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i + 1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) # modified filelink = self.filelink(url, path) # end modified except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading(head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules( object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection('Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda (key, value), s=self: s.modulelink(value)) result = result + self.bigsection('Modules', '#fffff', '#aa55cc', contents) if classes: classlist = map(lambda (key, value): value, classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name) ] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection('Classes', '#ffffff', '#ee77aa', join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection('Functions', '#ffffff', '#eeaa77', join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection('Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection('Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection('Credits', '#ffffff', '#7799ee', contents) return result
def display_class(cls, stream, level, args): #@DuplicatedSignature print " class {}".format(cls.__name__) title(stream, level, "Class " + cls.__name__) stream.write(inspect.getdoc(cls) or "") if cls.__init__ is object.__init__: spec = "" else: try: inspect.getargspec(cls.__init__) except: print " Skipping class spec" spec = "" else: spec = inspect.formatargspec(*inspect.getargspec(cls.__init__)) if args.mro: mro = inspect.getmro(cls)[1:-1] if mro: stream.write("\n\n") stream.write("*Method resolution order:* ") stream.write(", ".join(":obj:`~{0}.{1}`".format(c.__module__, c.__name__) for c in mro)) stream.write("\n\n.. class:: " + cls.__name__ + spec + "\n\n") class_stream = IndentStream(stream, " ") class_stream.write(inspect.getdoc(cls.__init__) or "") # Sort out aliases. thing_dict maps names (the names we're going to # document things under) to 2-tuples (thing, names), where thing is the # thing itself and names is a list of names under which it can be found # (including the key under which the tuple is registered in thing_dict) thing_dict = {} for name, kind, definer, thing in sorted(inspect.classify_class_attrs(cls)): if definer is cls and pydoc.visiblename(name, None, thing) and name != "__init__": # See if we've already seen this thing before. Python 3 # compatibility note: we have to iterate over a copy of the dict's # items since we could end up modifying the dict during iteration. for k, (v, names) in list(thing_dict.items()): # We have to use == here instead of "is" as the bound method # object returned for each attribute of a class is generated on # the fly, so it's different each time we request it. They # compare equal, though, if they wrap the same underlying # function, so using == works as expected. if v == thing: # We have, under the name k. Add an alias for it under our # current name. names.append(name) # If this thing has a __name__ and its __name__ is the # current name we're looking at, relocate the thing's entry # in thing_dict to list it under the current name. This # causes things to be preferentially documented under the # name with which they were actually defined. if getattr(thing, "__name__", None) == name: del thing_dict[k] thing_dict[name] = (v, names) # Also move the defined name so that it's first in the # list, which will cause it to be listed first in the # resulting documentation names.remove(name) names.insert(0, name) break else: # We haven't seen it before, so add a new entry for it. thing_dict[name] = (thing, [name]) for _, (thing, names) in sorted(thing_dict.iteritems()): # TODO: Handle nested classes here if should_document_as_method(thing): try: inspect.getargspec(thing) except: print " Couldn't get argspec, skipping {}".format(names) else: display_method(thing, class_stream, level + 1, args, cls, names) elif should_document_as_property(thing): display_property(thing, class_stream, level + 1, args, cls, names) else: print " Not a method or property, skipping {}".format(names) if args.inheritance: inheritance_dict = {} for name, kind, definer, thing in sorted(inspect.classify_class_attrs(cls)): if ( definer is not cls and definer is not object and pydoc.visiblename(name, None, thing) and name not in ["__dict__", "__weakref__"] and (should_document_as_method(thing) or should_document_as_property(thing))): inheritance_dict.setdefault(definer, []).append(name) for base_class in inspect.getmro(cls): if base_class in inheritance_dict: class_stream.write("\n\n*Members inherited from class* :obj:`~{0}.{1}`\\ *:* ".format(base_class.__module__, base_class.__name__)) class_stream.write(", ".join(":obj:`~{0}.{1}.{2}`".format(base_class.__module__, base_class.__name__, n) for n in inheritance_dict[base_class]))
def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" level = 2 # FIXME: use passed level in the future realname = object.__name__ name = name or realname bases = object.__bases__ doc = self.getdoc(object) components = {} def spill(msg, attrs, predicate): # `ok` are attributes to handle, `attrs` is what's left ok, attrs = pydoc._split_list(attrs, predicate) if ok: result = msg for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) result += self._docdescriptor(name, value, mod) else: result += self.document(value, name, mod, funcs, classes, mdict, object) # NOTE: this is that important side-effect you're looking for! components['docs'].append(result) return attrs def spilldescriptors(msg, attrs, predicate): # `ok` are attributes to handle, `attrs` is what's left ok, attrs = pydoc._split_list(attrs, predicate) if ok: result = msg for name, kind, homecls, value in ok: result += self._docdescriptor(name, value, mod) # NOTE: this is that important side-effect you're looking for! components['docs'].append(result) return attrs def spilldata(msg, attrs, predicate): # `ok` are attributes to handle, `attrs` is what's left ok, attrs = pydoc._split_list(attrs, predicate) if ok: result = msg for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)): doc = getattr(value, "__doc__", None) else: doc = None if doc is None: result += '<dl><dt>%s</dt></dl>\n' % base else: doc = self.markup(self.getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd>%s</dd>' % doc result += '<dl><dt>%s%s</dl>\n' % (base, doc) # NOTE: this is that important side-effect you're looking for! components['docs'].append(result) return attrs mro = collections.deque(inspect.getmro(object)) if len(mro) > 2: components[ 'mro'] = '<dl class="mro"><dt>Method resolution order:</dt>' for base in mro: components['mro'] += '<dd>%s</dd>' % self.classlink( base, object.__module__) components['mro'] += '</dl>' attrs = filter(lambda data: pydoc.visiblename(data[0], obj=object), pydoc.classify_class_attrs(object)) mdict = {} for key, kind, homecls, value in attrs: mdict[key] = anchor = '#' + name + '-' + key try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) pass try: # The value may not be hashable (e.g., a data attr with # a dict or list value). mdict[value] = anchor except TypeError: pass components['docs'] = [] # populated in spill* functions while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = pydoc._split_list(attrs, lambda t: t[2] is thisclass) # if thisclass is __builtin__.object: # 2.7 only, no clue why it wasn't just `object` in the first place. if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = '' else: tag = 'from %s' % self.classlink(thisclass, object.__module__) # Sort attrs by name. try: attrs.sort(key=lambda t: t[0]) except TypeError: attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat attrs = spill('<h4 class="head-methods">Methods %s</h4>' % tag, attrs, lambda t: t[1] == 'method') attrs = spill( '<h4 class="head-class-methods">Class methods %s</h4>' % tag, attrs, lambda t: t[1] == 'class method') attrs = spill( '<h4 class="head-static-methods">Static methods %s</h4>' % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors( '<h4 class="head-desc">Descriptors %s</h4>' % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata( '<h4 class="head-attrs">Attributes %s</h4>' % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited if name == realname: title = '<a name="%s" href="#%s">class <span class="class-name">%s</span></a>' % ( name, name, realname) else: title = '<span class="class-name">%s</span> = <a name="%s" href="#%s">class %s</a>' % ( name, name, name, realname) if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % ', '.join(parents) result = '<dt class="class">%s</dt>' % self.heading(level, title) result += '<dd class="class">' result += '<dd>\n%s\n</dd>' % doc if 'mro' in components: result += ' <div class="mro">%(mro)s</div>' % components result += '\n '.join(components['docs']) result += '</dd>' return result
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = name.split('.') links = [] for i in range(len(parts) - 1): links.append( '<a href="{}.html" class="docmodule_link">{}</a>'.format( '.'.join(parts[:i + 1]), parts[i])) head = '.'.join(links + parts[-1:]) try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = self.filelink(url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % ', '.join(info) docloc = self.getdocloc(object) if docloc is not None: docloc = ('<br><a href="%(docloc)s">Module Reference</a>' % locals()) else: docloc = '' extras = '<a href=".">index</a><br>' + filelink + docloc result = self.heading(head, extras) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all, object): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if key not in cdict: cdict[key] = cdict[base] = (modname + '.html#' + key) funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all, object): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all, object): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<code>{}</code>'.format(doc) result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules( object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', contents, css_class="package") elif modules: contents = self.multicolumn(modules, lambda t: self.modulelink(t[1])) result = result + self.bigsection( 'Modules', contents, css_class="module") if classes: classlist = [value for (key, value) in classes] contents = [ self.formattree(inspect.getclasstree(classlist, 1), name) ] for key, value in classes: contents.append( self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', ' '.join(contents), css_class="classes") if funcs: contents = [] for key, value in funcs: contents.append( self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', ' '.join(contents), css_class="functions") if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '<br>\n'.join(contents), css_class="data") if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( 'Author', contents, css_class="author") if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', contents, css_class="credits") return result