Python inspect.getdoc() Examples

The following are 30 code examples of inspect.getdoc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: docscrape.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def handle_method(method, method_name, class_name):
    method_errors = []

    # Skip out-of-library inherited methods
    module = inspect.getmodule(method)
    if module is not None:
        if not module.__name__.startswith('pylearn2'):
            return method_errors

    docstring = inspect.getdoc(method)
    if docstring is None:
        method_errors.append((class_name, method_name,
                              '**missing** method-level docstring'))
    else:
        method_errors = [
            (class_name, method_name, e) for e in
            NumpyFunctionDocString(docstring, method).get_errors()
        ]
    return method_errors 
Example #2
Source File: script.py    From lambda-packs with MIT License 6 votes vote down vote up
def analyse_action(func):
    """Analyse a function."""
    description = inspect.getdoc(func) or 'undocumented action'
    arguments = []
    args, varargs, kwargs, defaults = inspect.getargspec(func)
    if varargs or kwargs:
        raise TypeError('variable length arguments for action not allowed.')
    if len(args) != len(defaults or ()):
        raise TypeError('not all arguments have proper definitions')

    for idx, (arg, definition) in enumerate(zip(args, defaults or ())):
        if arg.startswith('_'):
            raise TypeError('arguments may not start with an underscore')
        if not isinstance(definition, tuple):
            shortcut = None
            default = definition
        else:
            shortcut, default = definition
        argument_type = argument_types[type(default)]
        if isinstance(default, bool) and default is True:
            arg = 'no-' + arg
        arguments.append((arg.replace('_', '-'), shortcut,
                          default, argument_type))
    return func, description, arguments 
Example #3
Source File: decorators.py    From jbox with MIT License 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    _check_for_unicode_literals()
    return cls(name=name or f.__name__.lower(),
               callback=f, params=params, **attrs) 
Example #4
Source File: script.py    From jbox with MIT License 6 votes vote down vote up
def analyse_action(func):
    """Analyse a function."""
    description = inspect.getdoc(func) or 'undocumented action'
    arguments = []
    args, varargs, kwargs, defaults = inspect.getargspec(func)
    if varargs or kwargs:
        raise TypeError('variable length arguments for action not allowed.')
    if len(args) != len(defaults or ()):
        raise TypeError('not all arguments have proper definitions')

    for idx, (arg, definition) in enumerate(zip(args, defaults or ())):
        if arg.startswith('_'):
            raise TypeError('arguments may not start with an underscore')
        if not isinstance(definition, tuple):
            shortcut = None
            default = definition
        else:
            shortcut, default = definition
        argument_type = argument_types[type(default)]
        if isinstance(default, bool) and default is True:
            arg = 'no-' + arg
        arguments.append((arg.replace('_', '-'), shortcut,
                          default, argument_type))
    return func, description, arguments 
Example #5
Source File: decorators.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    return cls(name=name or f.__name__.lower(),
               callback=f, params=params, **attrs) 
Example #6
Source File: decorators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    _check_for_unicode_literals()
    return cls(name=name or f.__name__.lower().replace('_', '-'),
               callback=f, params=params, **attrs) 
Example #7
Source File: purge.py    From lavatory with Apache License 2.0 6 votes vote down vote up
def apply_purge_policies(selected_repos, policies_path=None, dryrun=True, default=True):
    """Sets up the plugins to find purgable artifacts and delete them.

    Args:
        selected_repos (list): List of repos to run against.
        policies_path (str): Path to extra policies
        dryrun (bool): If true, will not actually delete artifacts.
        default (bool): If true, applies default policy to repos with no specific policy.
    """
    plugin_source = setup_pluginbase(extra_policies_path=policies_path)
    LOG.info("Applying retention policies to %s", ', '.join(selected_repos))
    for repository in selected_repos:
        artifactory_repo = Artifactory(repo_name=repository)
        policy = get_policy(plugin_source, repository, default=default)
        if not policy:
            continue
        LOG.info("Policy Docs: %s", inspect.getdoc(policy.purgelist))
        artifacts = policy.purgelist(artifactory_repo)
        purged_count = artifactory_repo.purge(dryrun, artifacts)
        LOG.info("Processed %s, Purged %s", repository, purged_count) 
Example #8
Source File: test_docstrings.py    From collectd-haproxy with MIT License 6 votes vote down vote up
def assert_docstring_includes_param_metadata(thing, path):
    if inspect.isclass(thing):
        return

    docstring = inspect.getdoc(thing)
    if not docstring:
        return

    for arg_name in inspect.getargspec(thing).args:
        if arg_name in ("self", "cls"):
            continue

        if ":param %s:" % arg_name not in docstring:
            raise AssertionError(
                "Missing :param: for arg %s of %s" % (arg_name, path)
            )
        if ":type %s:" % arg_name not in docstring:
            raise AssertionError(
                "Missing :type: for arg %s of %s" % (arg_name, path)
            ) 
Example #9
Source File: manage.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_func(name, func):

	doc = inspect.getdoc(func)
	sig = inspect.signature(func)

	if not doc or (doc and not doc.strip()):
		print("    {} -> {}".format(name.ljust(25), "UNDOCUMENTED"))
		if not sig.parameters:
			print("        No arguments")
		else:
			print("        Args: {}".format(sig))

	else:
		print("    {}".format(name))
		if not sig.parameters:
			print("        No arguments")
		else:
			print("        Args: {}".format(sig))
		doclines = doc.splitlines()
		for line in doclines:
			print("            -> {}".format(line))
	print() 
Example #10
Source File: serializer.py    From py2swagger with MIT License 6 votes vote down vote up
def _get_docstring_fields(self):
        """
        Collect custom serializer fields described in serializer docstring

        :rtype: OrderedDict
        """
        if not inspect.isclass(self.serializer):
            self.serializer = self.serializer.__class__

        parser = YAMLDocstringParser()

        for cls in inspect.getmro(self.serializer):
            parser.update(inspect.getdoc(cls))

        doc_fields = parser.schema.get('fields', OrderedDict())

        return doc_fields 
Example #11
Source File: loader.py    From friendly-telegram with GNU Affero General Public License v3.0 6 votes vote down vote up
def translateable_docstring(cls):
    @functools.wraps(cls.config_complete)
    def config_complete(self, *args, **kwargs):
        for command, func in get_commands(cls).items():

            @functools.wraps(func)
            def replacement(*args, **kwargs):
                return func(self, *args, **kwargs)
            replacement.__doc__ = self.strings["_cmd_doc_" + command]
            setattr(self, command, replacement)
        self.__doc__ = self.strings["_cls_doc"]
        return self.config_complete._old_(self, *args, **kwargs)
    config_complete._old_ = cls.config_complete
    cls.config_complete = config_complete
    for command, func in get_commands(cls).items():
        cls.strings["_cmd_doc_" + command] = inspect.getdoc(func)
    cls.strings["_cls_doc"] = inspect.getdoc(cls)
    return cls 
Example #12
Source File: docscrape.py    From skutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, func, role='func', doc=None, config={}):
        self._f = func
        self._role = role  # e.g. "func" or "meth"

        if doc is None:
            if func is None:
                raise ValueError("No function or docstring given")
            doc = inspect.getdoc(func) or ''
        NumpyDocString.__init__(self, doc)

        if not self['Signature'] and func is not None:
            func, func_name = self.get_func()
            try:
                # try to read signature
                argspec = inspect.getargspec(func)
                argspec = inspect.formatargspec(*argspec)
                argspec = argspec.replace('*', '\*')
                signature = '%s%s' % (func_name, argspec)
            except TypeError as e:
                signature = '%s()' % func_name
            self['Signature'] = signature 
Example #13
Source File: docscrape.py    From skutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
                 config=None):
        if not inspect.isclass(cls) and cls is not None:
            raise ValueError("Expected a class or None, but got %r" % cls)
        self._cls = cls

        if modulename and not modulename.endswith('.'):
            modulename += '.'
        self._mod = modulename

        if doc is None:
            if cls is None:
                raise ValueError("No class or documentation string given")
            doc = pydoc.getdoc(cls)

        NumpyDocString.__init__(self, doc)

        if config is not None and config.get('show_class_members', True):
            if not self['Methods']:
                self['Methods'] = [(name, '', '')
                                   for name in sorted(self.methods)]
            if not self['Attributes']:
                self['Attributes'] = [(name, '', '')
                                      for name in sorted(self.properties)] 
Example #14
Source File: docscrape.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_class(val, class_name):
    cls_errors = []
    docstring = inspect.getdoc(val)
    if docstring is None:
        cls_errors.append((class_name,
                           '**missing** class-level docstring'))
    else:
        cls_errors = [
            (e,) for e in
            NumpyClassDocString(docstring, class_name, val).get_errors()
        ]
        # Get public methods and parse their docstrings
        methods = dict(((name, func) for name, func in inspect.getmembers(val)
                        if not name.startswith('_') and callable(func) and
                        type(func) is not type))
        for m_name, method in six.iteritems(methods):
            # skip error check if the method was inherited
            # from a parent class (which means it wasn't
            # defined in this source file)
            if inspect.getmodule(method) is not None:
                continue
            cls_errors.extend(handle_method(method, m_name, class_name))
    return cls_errors 
Example #15
Source File: api_endpoint.py    From django-rest-framework-docs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __get_allowed_methods__(self):
        viewset_methods = []
        if self.drf_router:
            for prefix, viewset, basename in self.drf_router.registry:
                if self.callback.cls != viewset:
                    continue

                lookup = self.drf_router.get_lookup_regex(viewset)
                routes = self.drf_router.get_routes(viewset)

                for route in routes:

                    # Only actions which actually exist on the viewset will be bound
                    mapping = self.drf_router.get_method_map(viewset, route.mapping)
                    if not mapping:
                        continue

                    # Build the url pattern
                    regex = route.url.format(
                        prefix=prefix,
                        lookup=lookup,
                        trailing_slash=self.drf_router.trailing_slash
                    )
                    if self.pattern.regex.pattern == regex:
                        funcs, viewset_methods = zip(
                            *[(mapping[m], m.upper())
                              for m in self.callback.cls.http_method_names
                              if m in mapping]
                        )
                        viewset_methods = list(viewset_methods)
                        if len(set(funcs)) == 1:
                            self.docstring = inspect.getdoc(getattr(self.callback.cls, funcs[0]))

        view_methods = [force_str(m).upper()
                        for m in self.callback.cls.http_method_names
                        if self.is_method_allowed(self.callback.cls, m)]
        return sorted(viewset_methods + view_methods) 
Example #16
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #17
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def _docdescriptor(self, name, value, mod):
        results = []
        push = results.append

        if name:
            push('<dl><dt><strong>%s</strong></dt>\n' % name)
        if value.__doc__ is not None:
            doc = self.markup(getdoc(value), self.preformat)
            push('<dd><tt>%s</tt></dd>\n' % doc)
        push('</dl>\n')

        return ''.join(results) 
Example #18
Source File: cog.py    From discord.py with MIT License 5 votes vote down vote up
def description(self):
        """:class:`str`: Returns the cog's description, typically the cleaned docstring."""
        try:
            return self.__cog_cleaned_doc__
        except AttributeError:
            self.__cog_cleaned_doc__ = cleaned = inspect.getdoc(self)
            return cleaned 
Example #19
Source File: commandline_options.py    From sacred with MIT License 5 votes vote down vote up
def get_description(self):
        return inspect.getdoc(self.apply_function) or "" 
Example #20
Source File: introspection.py    From knack with MIT License 5 votes vote down vote up
def option_descriptions(operation):
    """ Extract parameter help from docstring of the command. """
    lines = inspect.getdoc(operation)

    if not lines:
        return {}

    param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype']
    option_descs = {}

    lines = lines.splitlines()
    index = 0
    while index < len(lines):
        l = lines[index]
        regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
        match = re.search(regex, l)
        if not match:
            index += 1
            continue

        # 'arg name' portion might have type info, we don't need it
        arg_name = str.split(match.group(2))[-1]
        arg_desc = match.group(3).strip()
        # look for more descriptions on subsequent lines
        index += 1
        while index < len(lines):
            temp = lines[index].strip()
            if any(temp.startswith(x) for x in param_breaks):
                break
            else:
                if temp:
                    arg_desc += (' ' + temp)
                index += 1

        option_descs[arg_name] = arg_desc

    return option_descs 
Example #21
Source File: utils.py    From spectree with Apache License 2.0 5 votes vote down vote up
def parse_comments(func):
    """
    parse function comments

    First line of comments will be saved as summary, and the rest
    will be saved as description.
    """
    doc = inspect.getdoc(func)
    if doc is None:
        return None, None
    doc = doc.split('\n', 1)
    if len(doc) == 1:
        return doc[0], None
    return doc[0], doc[1].strip() 
Example #22
Source File: tf_inspect.py    From lambda-packs with MIT License 5 votes vote down vote up
def getdoc(object):  # pylint: disable=redefined-builtin
  """TFDecorator-aware replacement for inspect.getdoc.

  Args:
    object: An object, possibly decorated.

  Returns:
    The docstring associated with the object.

  The outermost-decorated object is intended to have the most complete
  documentation, so the decorated parameter is not unwrapped.
  """
  return _inspect.getdoc(object) 
Example #23
Source File: introspection.py    From knack with MIT License 5 votes vote down vote up
def extract_full_summary_from_signature(operation):
    """ Extract the summary from the docstring of the command. """
    lines = inspect.getdoc(operation)
    regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
    summary = ''
    if lines:
        match = re.search(regex, lines)
        summary = lines[:match.regs[0][0]] if match else lines

    summary = summary.replace('\n', ' ').replace('\r', '')
    return summary 
Example #24
Source File: test_docstrings.py    From collectd-haproxy with MIT License 5 votes vote down vote up
def assert_docstring_present(thing, path):
    docstring = inspect.getdoc(thing)
    if not docstring or not docstring.strip():
        raise AssertionError("No docstring present for %s" % path) 
Example #25
Source File: api.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hubmethod(f):
    # type: (F) -> F
    f.__doc__ = "%s\n\n%s" % (
        "Alias for :py:meth:`sentry_sdk.Hub.%s`" % f.__name__,
        inspect.getdoc(getattr(Hub, f.__name__)),
    )
    return f 
Example #26
Source File: app.py    From core with MIT License 5 votes vote down vote up
def set_item(self, item):
        """Update elements to display information of a family item.

        Args:
            item (dict): A family item as registered with name, help and icon

        Returns:
            None

        """
        if not item:
            return

        # Support a font-awesome icon
        plugin = item.data(PluginRole)
        icon = getattr(plugin, "icon", "info-circle")
        assert isinstance(icon, six.string_types)
        icon = qtawesome.icon("fa.{}".format(icon), color="white")
        pixmap = icon.pixmap(self.SIZE, self.SIZE)
        pixmap = pixmap.scaled(self.SIZE, self.SIZE)

        # Parse a clean line from the Creator's docstring
        docstring = inspect.getdoc(plugin)
        help = docstring.splitlines()[0] if docstring else ""

        self.icon.setPixmap(pixmap)
        self.family.setText(item.data(FamilyRole))
        self.help.setText(help) 
Example #27
Source File: api.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def scopemethod(f):
    # type: (F) -> F
    f.__doc__ = "%s\n\n%s" % (
        "Alias for :py:meth:`sentry_sdk.Scope.%s`" % f.__name__,
        inspect.getdoc(getattr(Scope, f.__name__)),
    )
    return f 
Example #28
Source File: src2asciidoc.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _get_command_quickref(cmds):
    """Generate the command quick reference."""
    out = []
    out.append('[options="header",width="75%",cols="25%,75%"]')
    out.append('|==============')
    out.append('|Command|Description')
    for name, cmd in cmds:
        desc = inspect.getdoc(cmd.handler).splitlines()[0]
        out.append('|<<{name},{name}>>|{desc}'.format(name=name, desc=desc))
    out.append('|==============')
    return '\n'.join(out) 
Example #29
Source File: pydoc.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    result = _encode(result)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #30
Source File: metaclass_test.py    From custom_inherit with MIT License 5 votes vote down vote up
def test_property2():
    assert isinstance(Kid2.prop, property)
    assert getdoc(Kid2.prop) == "valid"