def hh(cmd = None): """Get help on a command.""" shell_funcs['hh'] = hh import pydoc from inspect import getargspec, formatargspec if not cmd: print "\nUse self.addrspace for Kernel/Virtual AS" print "Use self.addrspace.base for Physical AS" print "Use self.proc to get the current _EPROCESS object" print " and self.proc.get_process_address_space() for the current process AS" print " and self.proc.get_load_modules() for the current process DLLs\n" for f in sorted(shell_funcs): doc = pydoc.getdoc(shell_funcs[f]) synop, _full = pydoc.splitdoc(doc) print "{0:40} : {1}".format(f + formatargspec(*getargspec(shell_funcs[f])), synop) print "\nFor help on a specific command, type 'hh(<command>)'" elif type(cmd) == str: try: doc = pydoc.getdoc(shell_funcs[cmd]) except KeyError: print "No such command: {0}".format(cmd) return print doc else: doc = pydoc.getdoc(cmd) print doc
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): def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: doc_list = [] for name in sorted(items): try: doc_item = pydoc.getdoc(getattr(self._cls, name)) doc_list.append((name, '', splitlines_x(doc_item))) except AttributeError: pass # method doesn't exist self[field] = doc_list
def h(cmd=None): if cmd: L = [cmd,] else: L = cmds[:] for x in L: print x print pydoc.getdoc(eval(x))
def __init__(self, provider, permission, signatures, callable, name = None): """ Accept a signature in the form returned by xmlrpc_methods. """ import pydoc self.permission = permission self.callable = callable self.rpc_signatures = signatures self.description = pydoc.getdoc(callable) if name is None: self.name = provider.xmlrpc_namespace() + '.' + callable.__name__ else: self.name = provider.xmlrpc_namespace() + '.' + name self.namespace = provider.xmlrpc_namespace() self.namespace_description = pydoc.getdoc(provider)
def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and 'initializes x; see ' in pydoc.getdoc(obj.__init__)): return '', '' if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: sig = re.sub("^[^(]*", "", doc['Signature']) return sig, ''
def main(): usage = __import__(__name__).__doc__.strip() usage += "\n\nCommands:\n\n" commands = {} for func in sorted(COMMANDS): name = func.__name__.strip().replace("cmd_", "").replace("_", "-") commands[name] = func head, tail = pydoc.splitdoc(pydoc.getdoc(func)) cmd_help = textwrap.fill(tail, width=70).replace("\n", "\n ").strip() usage += "%s\n %s\n\n" % (head, cmd_help) usage = usage.strip() parser = OptionParser(usage=usage) parser.allow_interspersed_args = False (options, args) = parser.parse_args() if len(args) < 1: parser.error("No command given") cmd_name = args.pop(0) cmd = commands.get(cmd_name) if cmd is None: parser.error("Unknown command %s" % cmd_name) else: cmd(args)
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__ if name == realname: title = '### class ' + self.bold(realname) else: title = '### ' + self.bold(name) + ' = class ' + realname if bases: def makename(c, m=object.__module__): return pydoc.classname(c, m) parents = map(makename, bases) title = title + '(%s)' % ', '.join(parents) doc = pydoc.getdoc(object) contents = doc and doc + '\n' methods = pydoc.allmethods(object).items() methods.sort() for key, value in methods: if key.startswith('_'): continue contents = contents + '\n' + self.document(value, key, mod, object) if not contents: return title + '\n' return title + '\n' + self.indent(contents.rstrip()) + '\n'
def doc_element(self, element, namespace, qname): """ Document extension elements """ attributes = {'namespace-uri' : namespace or '', 'name' : qname, } self.start_element('element', attributes) desc = self.escape(pydoc.getdoc(element)) self.write_element('description', content=desc) if element.content: content = self.escape(str(element.content)) self.write_element('content', content=content) attributes = element.legalAttrs or {} for name, info in attributes.items(): attrs = {'name' : name, 'content' : str(info), 'required' : info.required and 'yes' or 'no', } if info.default: attrs['default'] = info.default self.start_element('attribute', attrs) desc = info.description or '' self.write_element('description', content=desc) self.end_element('attribute') self.end_element('element') return
def help(self, request): global _img topbar = '_' * 72 + '\n' # 72-character divider if hasattr(request, '__name__'): pydoc.pager(topbar + 'Help on ' + pydoc.text.bold(request.__name__) + ':\n\n' + pydoc.getdoc(request)) else: opts = _img.opts.__class__.__dict__ try: opt = opts[request] desc_list = str(opt.doc()).split('\n') desc = '\n\n'.join(desc_list) default_val = opt._default if isinstance(default_val, str): valstr = "'" + default_val + "'" else: valstr = str(default_val) default_val_text = 'Default value: ' + valstr if opt.group() != None and opt.group() != 'hidden': group_text = '\nBelongs to group: ' + opt.group() else: group_text = '' desc_text = lofar.bdsm.interface.wrap(desc, 72) desc_text = '\n'.join(desc_text) pydoc.pager(topbar + 'Help on the ' + pydoc.text.bold(request) + ' parameter:\n\n' + default_val_text + group_text + '\n\n' + desc_text) except(KeyError): print "Parameter '" + request + "' not recognized."
def pprinthook(value): """Pretty print an object to sys.stdout and also save it in __builtin__. """ if value is None: return __builtin__._ = value if isinstance(value, help_types): reprstr = repr(value) try: if inspect.isfunction(value): parts = reprstr.split(' ') parts[1] += inspect.formatargspec(*getargspec(value)) reprstr = ' '.join(parts) elif inspect.ismethod(value): parts = reprstr[:-1].split(' ') parts[2] += inspect.formatargspec(*getargspec(value)) reprstr = ' '.join(parts) + '>' except TypeError: pass sys.stdout.write(reprstr) sys.stdout.write('\n') if getattr(value, '__doc__', None): sys.stdout.write('\n') sys.stdout.write(pydoc.getdoc(value)) sys.stdout.write('\n') else: pphighlight(value, width=get_width() or 80)
def setup(args=None): # make sure our directory is at the front of sys.path module = metadata('backupmgr') # get the version and description from the source version = module.__version__ description = pydoc.splitdoc(pydoc.getdoc(module))[0] author, author_email = email.utils.parseaddr(module.__authors__[0]) # get the long description from README-type files long_description = [] for path in READMES: with open(os.path.join(SRCROOT, path), 'r') as fh: long_description.append(fh.read()) long_description = '\n'.join([ x for x in long_description if x ]) # use setuptools to do the rest setuptools.setup( name=pkg_resources.safe_name(module.__name__), packages=setuptools.find_packages(), version=version, description=description, author=author, author_email=author_email, zip_safe=True, #url=None, install_requires=["python-dateutil"], long_description=long_description, license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers' ])
def docroutine(self, obj, name=None, mod=None, cl=None): """Produce text documentation for a function or method obj.""" realname = obj.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(obj): obj = obj.__func__ if name == realname: title = self.bold(realname) else: if cl and realname in cl.__dict__ and cl.__dict__[realname] is obj: skipdocs = 1 title = '%s = %s' % (self.bold(name), realname) if inspect.isfunction(obj): args, varargs, keywords, defaults = inspect.getargspec(obj) argspec = inspect.formatargspec(args, varargs, keywords, defaults, formatvalue=self.formatvalue) else: argspec = '(...)' decl = "def %s(%s'):\n{: .lead}%s" % (title, escape_equal(self.emphasis(argspec[1:-1])), note) if skipdocs: return decl + '\n' else: doc = pydoc.getdoc(obj) or '' return '%s\n> %s' % (decl, (doc and self.indent(doc).rstrip() + '\n'))
def main(): """Run the metareview command-line interface.""" import optparse import pydoc docstring = pydoc.getdoc(sys.modules[__name__]) optparser = optparse.OptionParser(usage="%prog [-p PROJECT] [-u SSH_USER] " "[-s SSH_SERVER] REVIEWER", description=docstring) optparser.add_option('-p', '--project', default='openstack/heat', help='The project to look in. ' 'Defaults to "%default".') optparser.add_option('-u', '--ssh-user', default=None, help='The Gerrit username to connect with.') optparser.add_option('-s', '--ssh-server', default='review.openstack.org', help='The Gerrit server to connect to. ' 'Defaults to "%default".') options, args = optparser.parse_args() if len(args) < 1: raise Exception('No reviewer specified.') if len(args) > 1: raise Exception('Multiple reviewers specified.') return metareview(options, args[0], sys.stdout)
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if self.funcs.has_key(method_name): method = self.funcs[method_name] elif self.instance is not None: # Instance can implement _methodHelp to return help for a method if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) # if the instance has a _dispatch method then we # don't have enough information to provide help elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name, self.allow_dotted_names ) except AttributeError: pass # Note that we aren't checking that the method actually # be a callable object of some kind if method is None: return "" else: import pydoc return pydoc.getdoc(method)
def get_doc_object(obj, what=None, doc=None, config={}): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' if what == 'class': # It is important that the `doc=doc` is passed because # this function may be run the second time with a # prepared docstring `doc` and `obj=None` # In that case the prepared `doc` is used newdoc = SphinxTraitsDoc(obj, "", func_doc=SphinxFunctionDoc, doc=doc, config=config) if obj and looks_like_issubclass(obj, "HasTraits"): for name, trait, comment in comment_eater.get_class_traits(obj): # Exclude private traits. if not name.startswith('_'): newdoc['Traits'].append((name, trait, comment.splitlines())) return newdoc elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None and obj: doc = pydoc.getobj(obj) return SphinxDocString(pydoc.getdoc(obj), config=config)
def doc_arguments(self, object): self.start_element("arguments") if inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) if defaults: firstdefault = len(args) - len(defaults) for i in xrange(len(args)): if defaults and i >= firstdefault: default = repr(defaults[i - firstdefault]) else: default = None self.format_arg(args[i], default) if varargs: self.write_element("var-args", {"name": varargs}) if varkw: self.write_element("var-keywords", {"name": varkw}) else: arglist = "..." if inspect.isbuiltin(object): # Extract argument list from docstring match = _re_arglist.match(pydoc.getdoc(object)) if match: arglist = match.group("arglist") self.write_element("unknown", content=arglist) self.end_element("arguments") return
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 self._exclude_class_members = config.get('exclude_class_members', []) 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 methods(self): if self._cls is None: return [] return [name for name,func in inspect.getmembers(self._cls) if ((not name.startswith('_') or '.. shownumpydoc' in pydoc.getdoc(func)) and isinstance(func, collections.Callable))]
def write_doc(self, file): file.write(str(self.entry.home) + "\n") doc = pydoc.getdoc(self.entry.home) if doc: file.write(doc + "\n") for field in str(self.entry.info).split(', '): file.write("\t" + field + "\n")
def methodHelp(self, method_name): """ Name ---- `methodHelp` (`method_name`) Description ----------- Provide documentation for specified method. Arguments --------- `method_name`: string Name of the method whose documentation is required. Return value ------------ Returns the documentation for specified method. """ impl = self._context.mapper.lookup(method_name, self._context) if impl is None: return "" else: import pydoc return pydoc.getdoc(impl)
def process_routine(rootElt, obj, name, callables): if inspect.isfunction(obj): if _gIsPy3: argspec = inspect.getfullargspec(obj) else: argspec = inspect.getargspec(obj) sig = name + inspect.formatargspec(*argspec) else: sig = '' doc = getdoc(obj) or None call_sig_lines, description_lines = parsePyFuncDoc(doc, [sig]) if description_lines: doc = '\n'.join(parseDocSummary(description_lines)) if call_sig_lines: signature = '\n'.join(call_sig_lines) else: signature = sig if name == '__init__': if doc == obj.__init__.__doc__: doc = None if signature == obj.__init__.__doc__: signature = None funcElt = SubElement(rootElt, "scope", ilk="function", name=name) if doc: funcElt.set('doc', doc) if signature: funcElt.set('signature', signature) callables[name] = funcElt
def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): object = object.__func__ if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = inspect.getfullargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann, formatvalue=self.formatvalue, formatannotation=inspect.formatannotationrelativeto(object)) if realname == '<lambda>': title = self.bold(name) + ' lambda ' # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = "#### " + "def " + title + argspec + ':' + '\n' + note if skipdocs: return decl + '\n' else: doc = pydoc.getdoc(object) or '' return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
def Help(self, method=None): """Return help/usage information on a method. Args: method: string name like "GetUsageDataByHost" Returns: HTML documentat """ if method is None: obj = self title = 'GORD Help' text = 'This is the GORD server.' else: if method.startswith('_') or not hasattr(self, method): raise common.InvalidMethod(method) title = method obj = getattr(self, method) text = pydoc.getdoc(obj) other = ['Other Help:'] methods = dir(self) methods.sort() for d in methods: if d.startswith('_') or type(getattr(self, d)) is not types.MethodType: continue other.append(' %s' % d) footer = '\n'.join(other) return '%s\n\n%s\n\n%s\n\n' % (title, text, footer)
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % ( self.escape(anchor), self.escape(name)) if callable(object): argspec = str(signature(object)) else: argspec = '(...)' if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or "" else: docstring = pydoc.getdoc(object) decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) doc = self.markup( docstring, self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_class in _all_resources(prefix): self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, '%s') self.props_schemata = properties.schemata( self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata( self.resource_class.attributes_schema) if resource_class.support_status.status == support.DEPRECATED: sstatus = resource_class.support_status.to_dict() msg = _('%(status)s') if sstatus['message'] is not None: msg = _('%(status)s - %(message)s') para = nodes.inline('', msg % sstatus) warning = nodes.note('', para) section.append(warning) cls_doc = pydoc.getdoc(resource_class) if cls_doc: para = nodes.paragraph('', cls_doc) section.append(para) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_hot_syntax(section) self.contribute_yaml_syntax(section) self.contribute_json_syntax(section) return content
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_classes in _filter_resources( prefix, self.path(), self.statuses()): for resource_class in resource_classes: self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, '%s') self.props_schemata = properties.schemata( self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata( self.resource_class.attributes_schema) self._status_str(resource_class.support_status, section) cls_doc = pydoc.getdoc(resource_class) if cls_doc: # allow for rst in the class comments cls_nodes = core.publish_doctree(cls_doc).children section.extend(cls_nodes) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_hot_syntax(section) self.contribute_yaml_syntax(section) self.contribute_json_syntax(section) return content
def get_doc_object(obj, what=None, doc=None, config={}, builder=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] if builder is not None: template_loader = BuiltinTemplateLoader() template_loader.init(builder, dirs=template_dirs) else: template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) config['template'] = template_env.get_template('numpydoc_docstring.rst') if what == 'class': return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config)
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" anchor = (cl and cl.__name__ or "") + "-" + name note = "" title = '<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name)) if inspect.ismethod(object): args, varargs, varkw, defaults = inspect.getargspec(object) # exclude the argument bound to the instance, it will be # confusing to the non-Python user argspec = inspect.formatargspec(args[1:], varargs, varkw, defaults, formatvalue=self.formatvalue) elif inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=self.formatvalue) else: argspec = "(...)" if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or "" else: docstring = pydoc.getdoc(object) decl = title + argspec + (note and self.grey('<font face="helvetica, arial">%s</font>' % note)) doc = self.markup(docstring, self.preformat, funcs, classes, methods) doc = doc and "<dd><tt>%s</tt></dd>" % doc return "<dl><dt>%s</dt>%s</dl>\n" % (decl, doc)
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_classes in _filter_resources(prefix, self.path(), self.statuses()): for resource_class in resource_classes: self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, "%s") self.props_schemata = properties.schemata(self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata(self.resource_class.attributes_schema) # NOTE(prazumovsky): Adding base_attributes_schema dict to # Resource class should means adding new attributes from this # dict to documentation of each resource, else there is no # chance to learn about base attributes. self.attrs_schemata.update(self.resource_class.base_attributes_schema) self.update_policy_schemata = properties.schemata(self.resource_class.update_policy_schema) self._status_str(resource_class.support_status, section) cls_doc = pydoc.getdoc(resource_class) if cls_doc: # allow for rst in the class comments cls_nodes = core.publish_doctree(cls_doc).children section.extend(cls_nodes) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_update_policy(section) self.contribute_hot_syntax(section) return content
def getsdoc(obj): "like pydoc's getdoc, but shorter docs" doc = getdoc(obj) doclines = doc.split('\n') # Skip over python specific comments. index = 0 while index < len(doclines): if not _gPyModelineOrHashBangPat.match(doclines[index]): break index += 1 #doclines = parseDocSummary(doclines, limit=12) if len(doclines) > (index + 1): if not doclines[index+1].strip(): doclines.pop(index+1) doc = doclines[index] + '\n' + \ ' '.join([x.strip() for x in doclines[index+1:index+11]]) if not _gIsPy3: # Try encoding the docs, otherwise we'll run into problems when we want to # write out the tree data. try: doc = doc.decode("utf-8") except UnicodeDecodeError: try: doc = doc.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: doc = doc.decode("latin-1") return doc
def find_autosummary_in_docstring(name: str, module: str = None, filename: str = None ) -> List[AutosummaryEntry]: """Find out what items are documented in the given object's docstring. See `find_autosummary_in_lines`. """ if module: warnings.warn('module argument for find_autosummary_in_docstring() is deprecated.', RemovedInSphinx50Warning) try: real_name, obj, parent, modname = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return find_autosummary_in_lines(lines, module=name, filename=filename) except AttributeError: pass except ImportError as e: print("Failed to import '%s': %s" % (name, e)) except SystemExit: print("Failed to import '%s'; the module executes module level " "statement and it might call sys.exit()." % name) return []
def get_doc_object(obj, what=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' if what == 'class': doc = SphinxTraitsDoc(obj, '', func_doc=numpydoc.SphinxFunctionDoc) if looks_like_issubclass(obj, 'HasTraits'): for name, trait, comment in comment_eater.get_class_traits(obj): # Exclude private traits. if not name.startswith('_'): doc['Traits'].append((name, trait, comment.splitlines())) return doc elif what in ('function', 'method'): return numpydoc.SphinxFunctionDoc(obj, '') else: return numpydoc.SphinxDocString(pydoc.getdoc(obj))
def getpydocspec(f, func): try: argspec = pydoc.getdoc(f) except NameError: return None rx = re.compile(r'([a-zA-Z_][a-zA-Z0-9_]*?)\((.*?)\)') s = rx.search(argspec) if s is None: return None if not hasattr(f, '__name__') or s.groups()[0] != f.__name__: return None args = list() defaults = list() varargs = varkwargs = None kwonly_args = list() kwonly_defaults = dict() for arg in s.group(2).split(','): arg = arg.strip() if arg.startswith('**'): varkwargs = arg[2:] elif arg.startswith('*'): varargs = arg[1:] else: arg, _, default = arg.partition('=') if varargs is not None: kwonly_args.append(arg) if default: kwonly_defaults[arg] = default else: args.append(arg) if default: defaults.append(default) return [func, (args, varargs, varkwargs, defaults, kwonly_args, kwonly_defaults)]
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name)) if inspect.ismethod(object): args, varargs, varkw, defaults = inspect.getargspec(object.im_func) argspec = inspect.formatargspec(args[1:], varargs, varkw, defaults, formatvalue=self.formatvalue) elif inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=self.formatvalue) else: argspec = '(...)' if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or '' else: docstring = pydoc.getdoc(object) decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) doc = self.markup(docstring, self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
def doc_function(self, function, namespace, qname): """ Document extension functions """ from Ft.Xml.XPath.XPathTypes import g_xpathPrimitiveTypes attributes = { 'namespace-uri': namespace or '', 'name': qname, } self.start_element('function', attributes) desc = self.escape(pydoc.getdoc(function)) self.write_element('description', content=desc) result = getattr(function, 'result', None) result = g_xpathPrimitiveTypes.get(result, 'unknown') self.write_element('result', content=self.escape(result)) argtypes = getattr(function, 'arguments', ()) args, varargs, varkw, defaults = inspect.getargspec(function) firstdefault = len(args) - len(defaults or ()) # All extension functions take 'context' as their first argument so # start the index at 1 instead of 0. # IMPLEMENTATION NOTE: using map(None, ...) instead of zip to not # truncate the list if argtypes is shorter than args. for i, argtype in map(None, xrange(1, len(args)), argtypes): argname = str(args[i]) attributes = { 'name': argname, 'type': g_xpathPrimitiveTypes.get(argtype, argname), } if (i < firstdefault): attributes['required'] = 'yes' self.write_element('argument', attributes) self.end_element('function') return
def get_doc_object(obj, what=None, doc=None, config={}, builder=None): if what is None: if inspect.isclass(obj): what = "class" elif inspect.ismodule(obj): what = "module" elif isinstance(obj, Callable): what = "function" else: what = "object" if what == "class" and hasattr(obj, "run") and hasattr(obj, "audit"): what = "footing" template_dirs = [os.path.join(os.path.dirname(__file__), "templates")] if builder is not None: template_loader = BuiltinTemplateLoader() template_loader.init(builder, dirs=template_dirs) else: template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) config["template"] = template_env.get_template("footings_docstring.rst") if what == "footing": return SphinxFootingsDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what == "class": return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ("function", "method"): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config)
def getpydocspec(f, func): try: argspec = pydoc.getdoc(f) except NameError: return None s = getpydocspec_re.search(argspec) if s is None: return None if not hasattr(f, "__name__") or s.groups()[0] != f.__name__: return None args = list() defaults = list() varargs = varkwargs = None kwonly_args = list() kwonly_defaults = dict() for arg in s.group(2).split(","): arg = arg.strip() if arg.startswith("**"): varkwargs = arg[2:] elif arg.startswith("*"): varargs = arg[1:] else: arg, _, default = arg.partition("=") if varargs is not None: kwonly_args.append(arg) if default: kwonly_defaults[arg] = default else: args.append(arg) if default: defaults.append(default) return ArgSpec( args, varargs, varkwargs, defaults, kwonly_args, kwonly_defaults, None )
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_classes in _filter_resources( prefix, self.path(), self.statuses()): for resource_class in resource_classes: self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, '%s') self.props_schemata = properties.schemata( self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata( self.resource_class.attributes_schema) # NOTE(prazumovsky): Adding base_attributes_schema dict to # Resource class should means adding new attributes from this # dict to documentation of each resource, else there is no # chance to learn about base attributes. self.attrs_schemata.update( self.resource_class.base_attributes_schema) self.update_policy_schemata = properties.schemata( self.resource_class.update_policy_schema) self._status_str(resource_class.support_status, section) cls_doc = pydoc.getdoc(resource_class) if cls_doc: # allow for rst in the class comments cls_nodes = core.publish_doctree(cls_doc).children section.extend(cls_nodes) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_update_policy(section) self.contribute_hot_syntax(section) return content
def get_doc(obj, parent): """ Get the signature and docstring of the given object. Args: obj (routine): Function, method, methoddescriptor, or builtin. parent (class): Parent class or module of `obj`. Returns: tuple: (signature, docstring) """ doc = pydoc.getdoc(obj).strip(WHITESPACE) path = get_path(parent, obj) try: sig = inspect.signature(obj) results = (sig, doc) logger.debug("Found signature for `%s` using inspect.", path) except ValueError: results = _sig_fallback(obj, parent, doc) if not doc: logger.debug("Could not find docstring for `%s`.", path) return results
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 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 python_doc_help(request: Request, fun_name: str = None): if fun_name is None: return templates.TemplateResponse('show_text.html', {'request': request, 'text': '请在上方输入包名。', 'title': 'Python包文档'}) try: m = import_module(fun_name) try: f = m.__file__ except AttributeError: f = '无文件。' except (ImportError, ModuleNotFoundError): try: m = eval(fun_name) except Exception: m = False f = '查询出现错误。' else: f = '不是模块。' return templates.TemplateResponse('show_text.html', {'request': request, 'text': (f'原文件地址: {f}\n\n' + (pydoc.getdoc(m) if m else '未找到此包或函数名。')) if not m or pydoc.getdoc(m) else f'原文件地址: {f}\n\n{fun_name}无文档', 'title': fun_name + '的文档'})
def get_help(obj): """Returns the help of the given object. Inspired in the original pycomplete package """ paren = obj.rfind("(") if paren != -1: obj = obj[:paren] if obj.endswith("(") or obj.endswith("."): obj = obj[:-1] found = False pobj = None context_dict = 'subprogram_globals' if not obj in context.get_context(): context_dict = 'helper_globals' found = context.cimport(obj, context_dict) else: pobj = context.eval_code(obj) if obj not in context.subcontext_globals and found: pobj = context.eval_code(obj, context_dict) if not pobj: return "no help string for " + obj obj = context.eval_code(obj) return pydoc.getdoc(obj)
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) if not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute(self.instance, method_name, self.allow_dotted_names) except AttributeError: pass if method is None: return '' try: import pydoc return pydoc.getdoc(method) except ImportError: return method.__doc__
def decorator(function): hasArg, hasType, type = processWithOneArg(function) if isinstance(setup, SetupConfig): # Updating the replaced configuration documentation. assert isinstance(setup, SetupConfig) documentation = getdoc(function) if documentation: if setup.__doc__: setup.__doc__ += '\n%s' % documentation else: setup.__doc__ = documentation if isinstance(setup, SetupEvent): if hasArg: raise SetupError( 'No argument expected for function %s, when replacing an event' % function) if hasType: raise SetupError( 'No return type expected for function %s, when replacing an event' % function) return update_wrapper( register(SetupEventReplace(function, setup), callerLocals()), function) if hasType: if not isclass(type): raise SetupError( 'Expected a class as the return annotation for function %s' % function) else: types = (type, ) else: types = () return update_wrapper( register(SetupSourceReplace(function, setup, hasArg, types), callerLocals()), function)
def methodHelp(self, method_name): """ Name ---- `methodHelp` (`method_name`) Description ----------- Provide documentation for specified method. Arguments --------- `method_name`: string Name of the method whose documentation is required. Return value ------------ Returns the documentation for specified method. """ impl = self._context.mapper.lookup(method_name, self._context) if impl is None: return "" else: return pydoc.getdoc(impl)
def document(self, module): """ Produce documentation for a given module object. """ attributes = {'name': module.__name__} self.start_element('ext-module', attributes) desc = self.escape(pydoc.getdoc(module)) self.write_element('description', content=desc) namespaces = getattr(module, 'ExtNamespaces', {}) functions = getattr(module, 'ExtFunctions', {}) elements = getattr(module, 'ExtElements', {}) if namespaces: self.start_element('namespaces') for namespace_uri, prefix in namespaces.items(): self.doc_namespace(namespace_uri, prefix) self.end_element('namespaces') if functions: self.start_element('functions') for (namespace_uri, name), function in functions.items(): qname = self.make_qname(namespaces, namespace_uri, name) self.doc_function(function, namespace_uri, qname) self.end_element('functions') if elements: self.start_element('elements') for (namespace_uri, name), element in elements.items(): qname = self.make_qname(namespaces, namespace_uri, name) self.doc_element(element, namespace_uri, qname) self.end_element('elements') self.end_element('ext-module') return
def get_doc_object(obj, what=None, doc=None, config=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' if what == 'class' and obj is not None: doc = SphinxTraitsDoc(obj, '', func_doc=SphinxFunctionDoc, config=config) if looks_like_issubclass(obj, 'HasTraits'): for name, trait, comment in comment_eater.get_class_traits(obj): # Exclude private traits. if not name.startswith('_'): doc['Traits'].append((name, trait, comment.splitlines())) return doc elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None and obj: doc = pydoc.getobj(obj) return SphinxDocString(pydoc.getdoc(obj), config=config)
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls): raise ValueError("Initialise using a class. Got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename self._name = cls.__name__ self._func_doc = func_doc if doc is None: 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 help_method(request, pool): obj, method = get_object_method(request, pool) return pydoc.getdoc(getattr(obj, method))
def getdoc(self, object): doc = pydoc.getdoc(object) return '\n\n<pre class="doc" markdown="0">%s</pre>\n\n' % (doc)
def __init__(self, method, name=None, signature=None, docstring=None): self.method = method self.help = '' self.signature = [] self.name = '' self.permission = None self.login_required = False self.args = [] # set the method name based on @rpcmethod or the passed value # default to the actual method name if hasattr(method, 'external_name'): self.name = method.external_name elif name is not None: self.name = name else: try: # Python2 self.name = method.func_name except AttributeError: # Python3 self.name = method.__name__ # get the help string for each method if docstring is not None: self.help = docstring else: self.help = pydoc.getdoc(method) # set the permissions based on the decorator self.permission = getattr(method, 'permission', None) # set the permissions based on the decorator self.login_required = getattr(method, 'login_required', self.permission is not None) # use inspection (reflection) to get the arguments # If we're using Python 3, look for function annotations, but allow # the signature parameter override them. try: args, varargs, keywords, defaults = inspect.getargspec(method) # varargs = None # varkw = None # kwonlyargs = None # kwonlydefaults = None annotations = {} except ValueError: full_args = inspect.getfullargspec(method) args = full_args.args # varargs = full_args.varargs # varkw = full_args.varkw # defaults = full_args.defaults # kwonlyargs = full_args.kwonlyargs # kwonlydefaults = full_args.kwonlydefaults annotations = full_args.annotations self.args = [arg for arg in args if arg not in ('self', 'request')] self.signature.append(annotations.get('return', 'object')) for i, arg in enumerate(self.args): annotation = annotations.get(arg, None) if annotation: self.signature.append(annotation) else: try: self.signature.append(method.signature[i]) except (IndexError, AttributeError): self.signature.append('object') if hasattr(method, 'signature') and \ len(method.signature) == len(self.args) + 1: # use the @rpcmethod signature if it has the correct # number of args self.signature = method.signature elif signature is not None and len(self.args) + 1 == len(signature): # use the passed signature if it has the correct number # of arguments self.signature = signature
def _find_return_type(func): for line in pydoc.getdoc(func).splitlines(): if line.startswith(PYDOC_RETURN_LABEL): return line[len(PYDOC_RETURN_LABEL):].strip() return ""
def get_watch_argument_name(self, func): if PYDOC_FOLLOW_PARAM in pydoc.getdoc(func): return 'follow' else: return 'watch'
def test_class_axis(self): # https://github.com/pandas-dev/pandas/issues/18147 # no exception and no empty docstring assert pydoc.getdoc(Series.index)
def test_class_axis(self): # GH 18147 # no exception and no empty docstring assert pydoc.getdoc(DataFrame.index) assert pydoc.getdoc(DataFrame.columns)
def complete(self, tab=False): """Construct a full list of possible completions and construct and display them in a window. Also check if there's an available argspec (via the inspect module) and bang that on top of the completions too. The return value is whether the list_win is visible or not.""" self.docstring = None if not self.get_args(): self.argspec = None elif self.current_func is not None: try: self.docstring = pydoc.getdoc(self.current_func) except IndexError: self.docstring = None else: # pydoc.getdoc() returns an empty string if no # docstring was found if not self.docstring: self.docstring = None cw = self.cw() cs = self.current_string() if not cw: self.matches = [] self.matches_iter.update() if not (cw or cs): return bool(self.argspec) if cs and tab: # Filename completion self.matches = list() username = cs.split(os.path.sep, 1)[0] user_dir = os.path.expanduser(username) for filename in glob(os.path.expanduser(cs + '*')): if os.path.isdir(filename): filename += os.path.sep if cs.startswith('~'): filename = username + filename[len(user_dir):] self.matches.append(filename) self.matches_iter.update(cs, self.matches) return bool(self.matches) elif cs: # Do not provide suggestions inside strings, as one cannot tab # them so they would be really confusing. self.matches_iter.update() return False # Check for import completion e = False matches = importcompletion.complete(self.current_line(), cw) if matches is not None and not matches: self.matches = [] self.matches_iter.update() return False if matches is None: # Nope, no import, continue with normal completion try: self.completer.complete(cw, 0) except Exception: # This sucks, but it's either that or list all the exceptions that could # possibly be raised here, so if anyone wants to do that, feel free to send me # a patch. XXX: Make sure you raise here if you're debugging the completion # stuff ! e = True else: matches = self.completer.matches if (self.config.complete_magic_methods and self.buffer and self.buffer[0].startswith("class ") and self.current_line().lstrip().startswith("def ")): matches.extend(name for name in self.config.magic_methods if name.startswith(cw)) if not e and self.argspec: matches.extend(name + '=' for name in self.argspec[1][0] if isinstance(name, str) and name.startswith(cw)) if py3: matches.extend(name + '=' for name in self.argspec[1][4] if name.startswith(cw)) # unless the first character is a _ filter out all attributes starting with a _ if not e and not cw.split('.')[-1].startswith('_'): matches = [ match for match in matches if not match.split('.')[-1].startswith('_') ] if e or not matches: self.matches = [] self.matches_iter.update() if not self.argspec: return False else: # remove duplicates self.matches = sorted(set(matches)) if len(self.matches) == 1 and not self.config.auto_display_list: self.list_win_visible = True self.tab() return False self.matches_iter.update(cw, self.matches) return True
def get_macro_description(self, name): import pydoc return pydoc.getdoc(getattr(self, 'render_' + name.lower()))
def docmodule(self, object, name=None, mod=None, packageContext=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name 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) filelink = '<a href="file:%s">%s</a>' % (url, path) 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, ', ') result = self.heading(head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): if (inspect.getmodule(value) or object) is 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 not cdict.has_key(key): cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): if inspect.isbuiltin(value) or inspect.getmodule(value) is 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 key not in ['__builtins__', '__doc__']: data.append((key, value)) doc = self.markup(pydoc.getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc packageContext.clean(classes, object) packageContext.clean(funcs, object) packageContext.clean(data, object) if hasattr(object, '__path__'): modpkgs = [] modnames = [] for file in os.listdir(object.__path__[0]): path = os.path.join(object.__path__[0], file) modname = inspect.getmodulename(file) if modname and modname not in modnames: modpkgs.append((modname, name, 0, 0)) modnames.append(modname) elif pydoc.ispackage(path): modpkgs.append((file, name, 1, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) ## result = result + self.bigsection( ## 'Package Contents', '#ffffff', '#aa55cc', contents) result = result + self.moduleSection(object, packageContext) 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: try: contents.append(self.document(value, key)) except Exception, err: pass result = result + self.bigsection('Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
def run(self): env = self.state.document.settings.env # Interface function name = self.arguments[0].strip() obj = _import_object(name) args, varargs, keywords, defaults = inspect.getargspec(obj) # Implementation function impl_name = self.options['impl'] impl_obj = _import_object(impl_name) impl_args, impl_varargs, impl_keywords, impl_defaults = inspect.getargspec( impl_obj) # Format signature taking implementation into account args = list(args) defaults = list(defaults) def set_default(arg, value): j = args.index(arg) defaults[len(defaults) - (len(args) - j)] = value def remove_arg(arg): if arg not in args: return j = args.index(arg) if j < len(args) - len(defaults): del args[j] else: del defaults[len(defaults) - (len(args) - j)] del args[j] options = [] for j, opt_name in enumerate(impl_args): if opt_name in args: continue if j >= len(impl_args) - len(impl_defaults): options.append( (opt_name, impl_defaults[len(impl_defaults) - (len(impl_args) - j)])) else: options.append((opt_name, None)) set_default('options', dict(options)) set_default('method', self.options['method'].strip()) for arg in list(args): if arg not in impl_args and arg not in ('fun', 'x0', 'args', 'tol', 'callback', 'method', 'options'): remove_arg(arg) signature = inspect.formatargspec(args, varargs, keywords, defaults) # Produce output self.options['noindex'] = True self.arguments[0] = name + signature lines = textwrap.dedent(pydoc.getdoc(impl_obj)).splitlines() new_lines = [] for line in lines: if line.strip() == 'Options': new_lines.append("Other Parameters") elif line.strip() == "-" * len('Options'): new_lines.append("-" * len("Other Parameters")) else: new_lines.append(line) mangle_docstrings(env.app, 'function', name, None, None, new_lines) lines = new_lines new_lines = [] for line in lines: if line.strip() == ':Other Parameters:': new_lines.extend((BLURB % (name, )).splitlines()) new_lines.append(':Options:') else: new_lines.append(line) self.content = ViewList(new_lines, self.content.parent) return base_directive.run(self)
def test_member_deprecation(self): from deprecation_example import ExampleClass def base_deprecation(): warnings.warn("Non-drake warning", category=DeprecationWarning, stacklevel=2) # At this point, no other deprecations should have been thrown, so we # will test with the default `once` filter. with warnings.catch_warnings(record=True) as w: base_deprecation() # Should not appear. obj = ExampleClass() # Call each deprecated method / propery repeatedly; it should only # warn once per unique line of source code. # - Method. for _ in range(3): method = ExampleClass.deprecated_method self.assertEqual(obj.deprecated_method(), 1) # The next line will not show a warning. self.assertEqual(method(obj), 1) self.assertEqual(method.__doc__, ExampleClass.doc_method) # - Property. for _ in range(3): prop = ExampleClass.deprecated_prop self.assertEqual(obj.deprecated_prop, 2) # The next line will not show a warning. self.assertEqual(prop.__get__(obj), 2) self.assertEqual(prop.__doc__, ExampleClass.doc_prop) # Check warnings. self.assertEqual(len(w), 2) self._check_warning(w[0], ExampleClass.message_method) self._check_warning(w[1], ExampleClass.message_prop) # Because `once` uses a (somehow opaque) registry (not accessible via # `warnings.once*registry` or `_warnings.once_registry`), we must # change the filter to test behavior. `reload`ing `warnings` and/or # `_warnings` also does not work. # See caveat here with `catch_warnings`: # https://docs.python.org/2/library/warnings.html#testing-warnings # Enable deprecation warnings as well. with warnings.catch_warnings(record=True) as w: # N.B. This also overrides `DrakeDeprecationWarning` settings # because of ordering. We can redefine a filter for # `DrakeDeprecationWarning` if so desired. warnings.simplefilter("default", DeprecationWarning) base_deprecation() method = ExampleClass.deprecated_method self.assertEqual(len(w), 2) self._check_warning(w[0], "Non-drake warning", type=DeprecationWarning) self._check_warning(w[1], ExampleClass.message_method) # Edit the following flags to manually inspect the warnings generated. show_warnings = False if show_warnings: include_base_deprecations = False if include_base_deprecations: warnings.simplefilter("default", DeprecationWarning) else: # See above notes for why we have to set this. warnings.simplefilter("default", DrakeDeprecationWarning) for _ in range(3): base_deprecation() method = ExampleClass.deprecated_method method_extra = ExampleClass.deprecated_method prop = ExampleClass.deprecated_prop prop_extra = ExampleClass.deprecated_prop # N.B. `help(<module>)` is super verbose. print("Help text:\n{}".format( pydoc.getdoc(pydrake.util.deprecation))) # Manually set this back to `once`. warnings.simplefilter("ignored", DeprecationWarning) warnings.simplefilter("once", DrakeDeprecationWarning)