Python sphinx.util.inspect.safe_getattr() Examples

The following are 12 code examples of sphinx.util.inspect.safe_getattr(). 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 sphinx.util.inspect , or try the search function .
Example #1
Source File: importer.py    From cotk with Apache License 2.0 6 votes vote down vote up
def get_module_members(module: Any) -> List[Tuple[str, Any]]:
    """Get members of target module."""
    from autodoc import INSTANCEATTR

    members = {}  # type: Dict[str, Tuple[str, Any]]
    for name in dir(module):
        try:
            value = safe_getattr(module, name, None)
            members[name] = (name, value)
        except AttributeError:
            continue

    # annotation only member (ex. attr: int)
    if hasattr(module, '__annotations__'):
        for name in module.__annotations__:
            if name not in members:
                members[name] = (name, INSTANCEATTR)

    return sorted(list(members.values())) 
Example #2
Source File: sage_autodoc.py    From pyoptools with GNU General Public License v3.0 6 votes vote down vote up
def get_object_members(self, want_all):
        if want_all:
            if not hasattr(self.object, '__all__'):
                # for implicit module members, check __module__ to avoid
                # documenting imported objects
                return True, safe_getmembers(self.object)
            else:
                memberlist = self.object.__all__
        else:
            memberlist = self.options.members or []
        ret = []
        for mname in memberlist:
            try:
                ret.append((mname, safe_getattr(self.object, mname)))
            except AttributeError:
                self.directive.warn(
                    'missing attribute mentioned in :members: or __all__: '
                    'module %s, attribute %s' % (
                    safe_getattr(self.object, '__name__', '???'), mname))
        return False, ret 
Example #3
Source File: autoautosummary.py    From pyqgis with GNU General Public License v2.0 5 votes vote down vote up
def get_members(doc, obj, typ, include_public=None, signal=False, enum=False):
        try:
            if not include_public:
                include_public = []
            items = []

            for name in dir(obj):
                if name not in obj.__dict__.keys():
                    continue
                try:
                    chobj = safe_getattr(obj, name)
                    documenter = get_documenter(doc.settings.env.app, chobj, obj)
                    #cl = get_class_that_defined_method(chobj)
                    #print(name, chobj.__qualname__, type(chobj), issubclass(chobj, Enum), documenter.objtype)
                    if documenter.objtype == typ:
                        if typ == 'attribute':
                            if signal and type(chobj) != PyQt5.QtCore.pyqtSignal:
                                continue
                            if not signal and type(chobj) == PyQt5.QtCore.pyqtSignal:
                                continue
                        elif typ == 'class':
                            if enum and not issubclass(chobj, Enum):
                                continue
                            if not enum and issubclass(chobj, Enum):
                                continue
                        items.append(name)
                except AttributeError:
                    continue
            public = [x for x in items if x in include_public or not x.startswith('_')]
            return public, items
        except BaseException as e:
            print(str(e))
            raise e 
Example #4
Source File: conf.py    From nbodykit with GNU General Public License v3.0 5 votes vote down vote up
def get_members(clazz, obj, typ):
        names = set()
        items = []

        # the default dir
        for name in dir(obj):
            try:
                documenter = get_documenter(safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype == typ and not name.startswith('_'):
                if name not in AutoCosmoSummary.exclude:
                    items.append((clazz,name))
                    names.add(name) # keep track of method/attribute conflicts

        # the delegate dro
        for n in obj.dro:
            for name in dir(n):
                try:
                    documenter = get_documenter(safe_getattr(n, name), n)
                except AttributeError:
                    continue

                # dont do conflicts
                if name not in names:
                    if documenter.objtype == typ and not name.startswith('_'):
                        if name not in AutoCosmoSummary.exclude:
                            x = "%s.%s" %(n.__module__, n.__name__)
                            items.append((x,name))
                            names.add(name)

        return ['~%s.%s' %item for item in sorted(items, key=lambda x: x[1])] 
Example #5
Source File: conf.py    From civis-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_members(obj, typ, public_only=True):
        items = []
        for name in dir(obj):
            if public_only and name.startswith('_'):
                continue
            try:
                documenter = get_documenter(None, safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype == typ:
                items.append(name)
        return items 
Example #6
Source File: conf.py    From pyvista with MIT License 5 votes vote down vote up
def get_members(obj, typ, include_public=None):
        if not include_public:
            include_public = []
        items = []
        for name in sorted(obj.__dict__.keys()):#dir(obj):
            try:
                documenter = get_documenter(AutoAutoSummary.app, safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype in typ:
                items.append(name)
        public = [x for x in items if x in include_public or not x.startswith('_')]
        return public, items 
Example #7
Source File: sage_autodoc.py    From pyoptools with GNU General Public License v3.0 5 votes vote down vote up
def get_attr(obj, name, *defargs):
        """getattr() override for types such as Zope interfaces."""
        for typ, func in AutoDirective._special_attrgetters.iteritems():
            if isinstance(obj, typ):
                return func(obj, name, *defargs)
        return safe_getattr(obj, name, *defargs) 
Example #8
Source File: sage_autodoc.py    From pyoptools with GNU General Public License v3.0 5 votes vote down vote up
def add_content(self, more_content, no_docstring=False):
        if self.doc_as_attr:
            classname = safe_getattr(self.object, '__name__', None)
            if classname:
                content = ViewList(
                    [_('alias of :class:`%s`') % classname], source='')
                ModuleLevelDocumenter.add_content(self, content,
                                                  no_docstring=True)
        else:
            ModuleLevelDocumenter.add_content(self, more_content) 
Example #9
Source File: autosummary.py    From schedula with European Union Public License 1.1 5 votes vote down vote up
def get_members(app, obj, typ, include_public=(), imported=False):
    items = []
    for name in dir(obj):
        try:
            obj_name = safe_getattr(obj, name)
            try:
                documenter = get_documenter(app, obj_name, obj)
            except TypeError:
                documenter = get_documenter(obj_name, obj)

        except AttributeError:
            continue
        if documenter.objtype == typ:
            try:
                cond = imported or (obj_name.__module__ == obj.__name__)
            except AttributeError:
                cond = True

            if cond:
                items.append(name)
    skip = set(app.config.autosummary_skip_members)
    _n = '{}.%s'.format(obj.__name__)

    public = [
        x for x in items
        if (x in include_public or not x.startswith('_')) and _n % x not in skip
    ]
    return public, items 
Example #10
Source File: conf.py    From whatstk with GNU General Public License v3.0 5 votes vote down vote up
def get_members(obj, typ, include_public=None):
        if not include_public:
            include_public = []
        items = []
        for name in dir(obj):
            try:
                documenter = get_documenter(safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype == typ:
                items.append(name)
        public = [x for x in items if x in include_public or not x.startswith('_')]
        return public, items 
Example #11
Source File: autoautosummary.py    From biskit with GNU General Public License v3.0 5 votes vote down vote up
def get_members(obj, typ, include_public=None):
        if not include_public:
            include_public = []
        items = []
        for name in dir(obj):
            try:
                documenter = get_documenter(safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype == typ:
                items.append(name)
        public = [x for x in items if x in include_public or not x.startswith('_')]
        return public, items 
Example #12
Source File: conf.py    From pyvips with MIT License 4 votes vote down vote up
def setup(app):
    app.connect('autodoc-skip-member', skip_deprecated)
    try:
        from sphinx.ext.autosummary import Autosummary
        from sphinx.ext.autosummary import get_documenter
        from docutils.parsers.rst import directives
        from sphinx.util.inspect import safe_getattr

        class AutoAutoSummary(Autosummary):

            option_spec = {
                'methods': directives.unchanged,
                'attributes': directives.unchanged
            }

            required_arguments = 1

            @staticmethod
            def get_members(obj, typ, include_public=None):
                if not include_public:
                    include_public = []
                items = []
                for name in dir(obj):
                    try:
                        documenter = get_documenter(safe_getattr(obj, name),
                                                    obj)
                    except AttributeError:
                        continue
                    if documenter.objtype == typ:
                        items.append(name)
                public = [x for x in items
                          if x in include_public or not x.startswith('_')]
                return public, items

            def run(self):
                clazz = str(self.arguments[0])
                try:
                    (module_name, class_name) = clazz.rsplit('.', 1)
                    m = __import__(module_name, globals(), locals(),
                                   [class_name])
                    c = getattr(m, class_name)
                    if 'methods' in self.options:
                        _, methods = self.get_members(c,
                                                      'method', ['__init__'])

                        self.content = ["~%s.%s" % (clazz, method)
                                        for method in methods
                                        if not method.startswith('_')]
                    if 'attributes' in self.options:
                        _, attribs = self.get_members(c, 'attribute')
                        self.content = ["~%s.%s" % (clazz, attrib)
                                        for attrib in attribs
                                        if not attrib.startswith('_')]
                finally:
                    return super(AutoAutoSummary, self).run()

        app.add_directive('autoautosummary', AutoAutoSummary)
    except BaseException as e:
        raise e