Python inspect.isclass() Examples

The following are 30 code examples for showing how to use inspect.isclass(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module inspect , or try the search function .

Example 1
Project: py2swagger   Author: Arello-Mobile   File: filter.py    License: MIT License 6 votes vote down vote up
def get_filter_introspectors(view):

    from rest_framework import filters
    try:
        from django_filters.rest_framework.backends \
            import DjangoFilterBackend as third_party_django_filter_backend
    except ImportError:
        third_party_django_filter_backend = filters.DjangoFilterBackend

    filters_map = {
        third_party_django_filter_backend: DjangoFilterBackendIntrospector,
        filters.DjangoFilterBackend: DjangoFilterBackendIntrospector,
        filters.OrderingFilter: OrderingFilterBackendIntrospector,
    }
    filter_backends = getattr(view, 'filter_backends', [])
    introspectors = []

    for backend in filter_backends:
        backend = backend if inspect.isclass(backend) else backend.__class__
        introspectors.append(
            filters_map.get(backend, BaseFilterBackendIntrospector)(view, backend)
        )

    return introspectors 
Example 2
Project: py2swagger   Author: Arello-Mobile   File: serializer.py    License: MIT License 6 votes vote down vote up
def _get_name(self):
        """
        :return: Serializer name
        :rtype: str
        """
        serializer = self.serializer

        if inspect.isclass(serializer):
            name = serializer.__name__
        else:
            name = serializer.__class__.__name__

        if name == 'DefaultSerializer' and issubclass(serializer, ModelSerializer):
            model_name = self.serializer.Meta.model.__name__
            name = '{0}Serializer'.format(model_name.strip())
        return name 
Example 3
Project: py2swagger   Author: Arello-Mobile   File: serializer.py    License: 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 4
def __init__(self, *args, **kwargs):
            self.child = kwargs.pop('child', copy.deepcopy(self.child))

            self.permission_classes = self.child.permission_classes
            self.check_permission = self.child.check_permission

            self.allow_empty = kwargs.pop('allow_empty', True)

            assert self.child is not None, '`child` is a required argument.'
            assert not inspect.isclass(self.child), '`child` has not been instantiated.'

            # TODO: diagnose/address bad-super-call issue
            # pylint: disable=bad-super-call
            super(ListSerializer, self).__init__(*args, **kwargs)

            self.child.bind(field_name='', parent=self) 
Example 5
Project: oscrypto   Author: wbond   File: _types.py    License: MIT License 6 votes vote down vote up
def type_name(value):
    """
    Returns a user-readable name for the type of an object

    :param value:
        A value to get the type name of

    :return:
        A unicode string of the object's type name
    """

    if inspect.isclass(value):
        cls = value
    else:
        cls = value.__class__
    if cls.__module__ in set(['builtins', '__builtin__']):
        return cls.__name__
    return '%s.%s' % (cls.__module__, cls.__name__) 
Example 6
Project: jawfish   Author: war-and-code   File: pydoc.py    License: MIT License 6 votes vote down vote up
def document(self, object, name=None, *args):
        """Generate documentation for an object."""
        args = (object, name) + args
        # 'try' clause is to attempt to handle the possibility that inspect
        # identifies something in a way that pydoc itself has issues handling;
        # think 'super' and how it is a descriptor (which raises the exception
        # by lacking a __name__ attribute) and an instance.
        if inspect.isgetsetdescriptor(object): return self.docdata(*args)
        if inspect.ismemberdescriptor(object): return self.docdata(*args)
        try:
            if inspect.ismodule(object): return self.docmodule(*args)
            if inspect.isclass(object): return self.docclass(*args)
            if inspect.isroutine(object): return self.docroutine(*args)
        except AttributeError:
            pass
        if isinstance(object, property): return self.docproperty(*args)
        return self.docother(*args) 
Example 7
Project: nose-htmloutput   Author: ionelmc   File: __init__.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def nice_classname(obj):
    """Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'

    """
    if inspect.isclass(obj):
        cls_name = obj.__name__
    else:
        cls_name = obj.__class__.__name__
    mod = inspect.getmodule(obj)
    if mod:
        name = mod.__name__
        # jython
        if name.startswith('org.python.core.'):
            name = name[len('org.python.core.'):]
        return "%s.%s" % (name, cls_name)
    else:
        return cls_name 
Example 8
Project: DidYouMean-Python   Author: SylvainDe   File: didyoumean_internal.py    License: MIT License 6 votes vote down vote up
def get_types_for_str(tp_name, frame):
    """Get a list of candidate types from a string.

    String corresponds to the tp_name as described in :
    https://docs.python.org/2/c-api/typeobj.html#c.PyTypeObject.tp_name
    as it is the name used in exception messages. It may include full path
    with module, subpackage, package but this is just removed in current
    implementation to search only based on the type name.

    Lookup uses both class hierarchy and name lookup as the first may miss
    old style classes on Python 2 and second does find them.
    Just like get_types_for_str_using_inheritance, this needs to be called
    as late as possible but because it requires a frame, there is not much
    choice anyway.
    """
    name = tp_name.split('.')[-1]
    res = set.union(
        get_types_for_str_using_inheritance(name),
        get_types_for_str_using_names(name, frame))
    assert all(inspect.isclass(t) and t.__name__ == name for t in res)
    return res 
Example 9
Project: me-ica   Author: ME-ICA   File: test_nodes_generic.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def generate_nodes_list(nodes_dicts):
    nodes_list = []
    # append nodes with additional arguments or supervised if they exist
    visited = []
    for dct in nodes_dicts:
        klass = dct['klass']
        if type(klass) is str:
            # some of the nodes on the list may be optional
            if not hasattr(nodes, klass): continue
            # transform class name into class (needed by automatic tests)
            klass = getattr(nodes, klass)
            dct['klass'] = klass
        nodes_list.append(dct)
        visited.append(klass)
    # append all other nodes in mdp.nodes
    for attr in dir(nodes):
        if attr[0] == '_':
            continue
        attr = getattr(nodes, attr)
        if (inspect.isclass(attr)
            and issubclass(attr, mdp.Node)
            and attr not in visited
            and attr not in EXCLUDE_NODES):
            nodes_list.append(attr)
    return nodes_list 
Example 10
Project: loaner   Author: google   File: gng_impl.py    License: Apache License 2.0 6 votes vote down vote up
def _get_oauth_scopes(modules=_API_CLIENT_MODULES):
  """Retrieves all OAuth2 Scopes required for management.

  Args:
    modules: Sequence[module], a sequence of modules to extract OAuth2 scopes
        from.

  Returns:
    A list of all of the OAuth2 Scopes required for management.
  """
  scopes = []
  for client in modules:
    for name, cls in inspect.getmembers(client, inspect.isclass):
      if name.endswith('API') and hasattr(cls, 'SCOPES'):
        scopes.extend(cls.SCOPES)
  return sorted(list(set(scopes))) 
Example 11
Project: sk1-wx   Author: sk1project   File: ctxpanel.py    License: GNU General Public License v3.0 6 votes vote down vote up
def rebuild(self, *_args):
        mode = self.get_mode()
        if mode == self.mode:
            return
        self.fixator.update()
        self.hide(update=False)
        for item in self.plugins:
            item.hide()
            self.remove(item)
        self.plugins = []
        if mode:
            for item in mode:
                plg = self.plugins_dict[item]
                if inspect.isclass(plg):
                    self.plugins_dict[item] = plg(self.app, self)
                    self.plugins_dict[item].update()
                self.pack(self.plugins_dict[item], fill=True)
                self.plugins_dict[item].show(update=False)
                self.plugins.append(self.plugins_dict[item])
        self.layout()
        self.show()
        self.mode = mode 
Example 12
Project: BASS   Author: Cisco-Talos   File: thread.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed") 
Example 13
Project: mmdetection   Author: open-mmlab   File: transforms.py    License: Apache License 2.0 5 votes vote down vote up
def albu_builder(self, cfg):
        """Import a module from albumentations.

        It inherits some of :func:`build_from_cfg` logic.

        Args:
            cfg (dict): Config dict. It should at least contain the key "type".

        Returns:
            obj: The constructed object.
        """

        assert isinstance(cfg, dict) and 'type' in cfg
        args = cfg.copy()

        obj_type = args.pop('type')
        if mmcv.is_str(obj_type):
            if albumentations is None:
                raise RuntimeError('albumentations is not installed')
            obj_cls = getattr(albumentations, obj_type)
        elif inspect.isclass(obj_type):
            obj_cls = obj_type
        else:
            raise TypeError(
                f'type must be a str or valid type, but got {type(obj_type)}')

        if 'transforms' in args:
            args['transforms'] = [
                self.albu_builder(transform)
                for transform in args['transforms']
            ]

        return obj_cls(**args) 
Example 14
Project: neural-fingerprinting   Author: StephanZheng   File: docscrape.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, cls, modulename=''):
        if not inspect.isclass(cls):
            raise ValueError("Initialise using an object")
        self._cls = cls

        if modulename and not modulename.endswith('.'):
            modulename += '.'
        self._mod = modulename
        self._name = cls.__name__ 
Example 15
Project: knob   Author: francozappa   File: cmds.py    License: MIT License 5 votes vote down vote up
def getCmdList():
    """ Returns a list of all commands which are defined in this cmds.py file.
    This is done by searching for all subclasses of Cmd
    """
    return [obj for name, obj in inspect.getmembers(sys.modules[__name__]) 
                            if inspect.isclass(obj) and issubclass(obj, Cmd)][1:] 
Example 16
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def __set__(self, obj, value):
        if not self.fset:
            raise MXNetError("cannot use the setter: %s to set attribute" % obj.__name__)
        if inspect.isclass(obj):
            type_ = obj
            obj = None
        else:
            type_ = type(obj)
        return self.fset.__get__(obj, type_)(value) 
Example 17
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def add_fileline_to_docstring(module, incursive=True):
    """Append the definition position to each function contained in module.

    Examples
    --------
    # Put the following codes at the end of a file
    add_fileline_to_docstring(__name__)
    """

    def _add_fileline(obj):
        """Add fileinto to a object.
        """
        if obj.__doc__ is None or 'From:' in obj.__doc__:
            return
        fname = inspect.getsourcefile(obj)
        if fname is None:
            return
        try:
            line = inspect.getsourcelines(obj)[-1]
        except IOError:
            return
        obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)

    if isinstance(module, str):
        module = sys.modules[module]
    for _, obj in inspect.getmembers(module):
        if inspect.isbuiltin(obj):
            continue
        if inspect.isfunction(obj):
            _add_fileline(obj)
        if inspect.ismethod(obj):
            _add_fileline(obj.__func__)
        if inspect.isclass(obj) and incursive:
            add_fileline_to_docstring(obj, False) 
Example 18
Project: DOTA_models   Author: ringringyi   File: registry.py    License: Apache License 2.0 5 votes vote down vote up
def _GetClass(name):
  """Looks up a class by name.

  Args:
    name: The fully-qualified type name of the class to return.

  Returns:
    The class associated with the |name|, or None on error.
  """
  elements = name.split('.')

  # Need at least "module.Class".
  if len(elements) < 2:
    logging.debug('Malformed type: "%s"', name)
    return None
  module_path = '.'.join(elements[:-1])
  class_name = elements[-1]

  # Import the module.
  try:
    __import__(module_path)
  except ImportError as e:
    logging.debug('Unable to find module "%s": "%s"', module_path, e)
    return None
  module = sys.modules[module_path]

  # Look up the class.
  if not hasattr(module, class_name):
    logging.debug('Name "%s" not found in module: "%s"', class_name,
                  module_path)
    return None
  class_obj = getattr(module, class_name)

  # Check that it is actually a class.
  if not inspect.isclass(class_obj):
    logging.debug('Name does not refer to a class: "%s"', name)
    return None
  return class_obj 
Example 19
Project: py2swagger   Author: Arello-Mobile   File: utils.py    License: MIT License 5 votes vote down vote up
def get_mro_list(instance, only_parents=True):
    mro = []
    if inspect.isclass(instance):
        mro = inspect.getmro(instance)
        if only_parents:
            mro = mro[1:]
    return mro 
Example 20
Project: securityheaders   Author: koenbuyens   File: checkerfactory.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.clazzes = dict()
        path = securityheaders.checkers.__path__[0]
        root = Node("Checker")
        for loader, module_name, is_pkg in  pkgutil.walk_packages(securityheaders.checkers.__path__):
            module = loader.find_module(module_name).load_module(module_name)
            for name, obj in inspect.getmembers(module):
                if hasattr(obj, "__name__") and obj.__name__ not in self.clazzes.keys() and inspect.isclass(obj) and issubclass(obj, Checker):
                    self.clazzes[obj.__name__] = obj
        self.tree = self.__getnames_as_tree__(self.clazzes) 
Example 21
Project: mx   Author: graalvm   File: mx_compat.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _ensureCompatLoaded():
    if not _versionsMap:

        def flattenClassTree(tree):
            root = tree[0][0]
            assert isinstance(root, type), root
            yield root
            if len(tree) > 1:
                assert len(tree) == 2
                rest = tree[1]
                assert isinstance(rest, list), rest
                for c in flattenClassTree(rest):
                    yield c

        classes = []
        regex = re.compile(r'^MxCompatibility[0-9a-z]*$')
        for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass):
            m = regex.match(name)
            if m:
                classes.append(clazz)

        previousVersion = None
        for clazz in flattenClassTree(inspect.getclasstree(classes)):
            if clazz == object:
                continue
            assert previousVersion is None or previousVersion < clazz.version()
            previousVersion = clazz.version()
            _versionsMap[previousVersion] = clazz() 
Example 22
Project: aws-ops-automator   Author: awslabs   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _get_action_class_from_module(class_module):
    """
    Find the action class in a module using naming pattern.
    :param class_module: The module
    :return: Class for the action, None if no action class was found
    """
    for cls in inspect.getmembers(class_module, inspect.isclass):
        if cls[1].__module__ != class_module.__name__ or not cls[1].__name__.endswith(ACTION):
            continue
        return cls
    return None 
Example 23
Project: aws-ops-automator   Author: awslabs   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _get_service_class(service_module):
    """
    Gets the service class from the module using naming pattern, the name of the class must end with "Service"
    :param service_module: The service class from the module, None if no service class was found
    :return:
    """
    for cls in inspect.getmembers(service_module, inspect.isclass):
        if cls[1].__module__ != service_module.__name__ or not cls[1].__name__.endswith(SERVICE):
            continue
        return cls
    return None 
Example 24
Project: aws-ops-automator   Author: awslabs   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _get_handler_class(handler_module):
    """
    Gets the service class from the module using naming pattern, the name of the class must end with "Service"
    :param handler_module: The service class from the module, None if no service class was found
    :return:
    """
    for cls in inspect.getmembers(handler_module, inspect.isclass):
        if cls[1].__module__ != handler_module.__name__ or not cls[1].__name__.endswith(HANDLER):
            continue
        return cls
    return None 
Example 25
Project: EXOSIMS   Author: dsavransky   File: test_get_module.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_module(self, m, modtype=None):
        self.assertTrue(inspect.isclass(m))
        self.assertTrue(hasattr(m, '_modtype'))
        if modtype:
            self.assertEqual(m._modtype, modtype)

    ##############
    ## Tests for  case 1: source is explicitly named
    ############## 
Example 26
def is_subclass_of(variable, required_class):
    return inspect.isclass(variable) and issubclass(variable, required_class) 
Example 27
Project: ipygee   Author: fitoprincipe   File: threading.py    License: MIT License 5 votes vote down vote up
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed") 
Example 28
Project: matchpy   Author: HPAC   File: test_expressions.py    License: MIT License 5 votes vote down vote up
def test_getitem(self, position, expected_result):
        if inspect.isclass(expected_result) and issubclass(expected_result, Exception):
            with pytest.raises(expected_result):
                result = self.GETITEM_TEST_EXPRESSION[position]
                print(result)
        else:
            result = self.GETITEM_TEST_EXPRESSION[position]
            assert result == expected_result 
Example 29
Project: matchpy   Author: HPAC   File: test_expressions.py    License: MIT License 5 votes vote down vote up
def test_getitem_slice(self, start, end, expected_result):
        if inspect.isclass(expected_result) and issubclass(expected_result, Exception):
            with pytest.raises(expected_result):
                result = self.GETITEM_TEST_EXPRESSION[start:end]
                print(result)
        else:
            result = self.GETITEM_TEST_EXPRESSION[start:end]
            assert result == expected_result 
Example 30
Project: rtp_cluster   Author: sippy   File: objgraph.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show_backrefs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10,
                  highlight=None):
    """Generate an object reference graph ending at ``objs``

    The graph will show you what objects refer to ``objs``, directly and
    indirectly.

    ``objs`` can be a single object, or it can be a list of objects.

    Produces a Graphviz .dot file and spawns a viewer (xdot) if one is
    installed, otherwise converts the graph to a .png image.

    Use ``max_depth`` and ``too_many`` to limit the depth and breadth of the
    graph.

    Use ``filter`` (a predicate) and ``extra_ignore`` (a list of object IDs) to
    remove undesired objects from the graph.

    Use ``highlight`` (a predicate) to highlight certain graph nodes in blue.

    Examples:

        >>> show_backrefs(obj)
        >>> show_backrefs([obj1, obj2])
        >>> show_backrefs(obj, max_depth=5)
        >>> show_backrefs(obj, filter=lambda x: not inspect.isclass(x))
        >>> show_backrefs(obj, highlight=inspect.isclass)
        >>> show_backrefs(obj, extra_ignore=[id(locals())])

    """
    show_graph(objs, max_depth=max_depth, extra_ignore=extra_ignore,
               filter=filter, too_many=too_many, highlight=highlight,
               edge_func=gc.get_referrers, swap_source_target=False)