Python inspect.isclass() Examples

The following are 30 code examples of inspect.isclass(). 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: fields.py    From django-rest-serializer-field-permissions with GNU General Public License v3.0 7 votes vote down vote up
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 #2
Source File: filter.py    From py2swagger with 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 #3
Source File: gng_impl.py    From loaner with 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 #4
Source File: _types.py    From oscrypto with 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 #5
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 #6
Source File: serializer.py    From py2swagger with 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 #7
Source File: pydoc.py    From jawfish with 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 #8
Source File: __init__.py    From nose-htmloutput with 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 #9
Source File: ctxpanel.py    From sk1-wx with 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 #10
Source File: test_nodes_generic.py    From me-ica with 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 #11
Source File: didyoumean_internal.py    From DidYouMean-Python with 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 #12
Source File: base.py    From transformpy with MIT License 5 votes vote down vote up
def init(self, outputter, *args, **kwargs):
        self.is_function = inspect.isfunction(outputter)
        if not self.is_function:
            if inspect.isclass(outputter):
                outputter = outputter(*args, **kwargs)
            assert outputter.type == TransformType.SINK
        self.__outputter = outputter 
Example #13
Source File: registry.py    From AerialDetection with Apache License 2.0 5 votes vote down vote up
def _register_module(self, module_class):
        """Register a module.

        Args:
            module (:obj:`nn.Module`): Module to be registered.
        """
        if not inspect.isclass(module_class):
            raise TypeError('module must be a class, but got {}'.format(
                type(module_class)))
        module_name = module_class.__name__
        if module_name in self._module_dict:
            raise KeyError('{} is already registered in {}'.format(
                module_name, self.name))
        self._module_dict[module_name] = module_class 
Example #14
Source File: ltmain.py    From Python with MIT License 5 votes vote down vote up
def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    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:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
        raise SystemError("PyThreadState_SetAsyncExc failed") 
Example #15
Source File: registry.py    From AerialDetection with Apache License 2.0 5 votes vote down vote up
def build_from_cfg(cfg, registry, default_args=None):
    """Build a module from config dict.

    Args:
        cfg (dict): Config dict. It should at least contain the key "type".
        registry (:obj:`Registry`): The registry to search the type from.
        default_args (dict, optional): Default initialization arguments.

    Returns:
        obj: The constructed object.
    """
    assert isinstance(cfg, dict) and 'type' in cfg
    assert isinstance(default_args, dict) or default_args is None
    args = cfg.copy()
    obj_type = args.pop('type')
    if mmcv.is_str(obj_type):
        obj_type = registry.get(obj_type)
        if obj_type is None:
            raise KeyError('{} is not in the {} registry'.format(
                obj_type, registry.name))
    elif not inspect.isclass(obj_type):
        raise TypeError('type must be a str or valid type, but got {}'.format(
            type(obj_type)))
    if default_args is not None:
        for name, value in default_args.items():
            args.setdefault(name, value)
    return obj_type(**args) 
Example #16
Source File: base.py    From transformpy with MIT License 5 votes vote down vote up
def __ins(self, obj, type, args, kwargs):
        if inspect.isclass(obj):
            obj = obj(*args, **kwargs)
        elif not isinstance(obj, TransformPipe) and hasattr(obj, '__call__'):
            if type is not 'output':
                obj = FunctionWrapperPipe(obj, type)
            else:
                obj = FunctionWrapperSinkPipe(obj, type)
        return obj 
Example #17
Source File: canvas.py    From sk1-wx with GNU General Public License v3.0 5 votes vote down vote up
def destroy(self):
        self.timer.stop()
        self.renderer.destroy()
        self.hit_surface.destroy()
        items = self.ctrls.keys()
        for item in items:
            if not inspect.isclass(self.ctrls[item]):
                self.ctrls[item].destroy()
        items = self.__dict__.keys()
        for item in items:
            self.__dict__[item] = None

    # ----- CONTROLLERS 
Example #18
Source File: decorators.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, o):

        if isfunction(o):
            # We must wait to finalize configuration as the class containing this function is under construction
            # at the time this call to decorate a member function. This will be handled in the call to
            # o.ConfigurationSettings.fix_up(o) in the elif clause of this code block.
            o._settings = self.settings
        elif isclass(o):

            # Set command name

            name = o.__name__
            if name.endswith('Command'):
                name = name[:-len('Command')]
            o.name = six.text_type(name.lower())

            # Construct ConfigurationSettings instance for the command class

            o.ConfigurationSettings = ConfigurationSettingsType(
                module=o.__module__ + '.' + o.__name__,
                name='ConfigurationSettings',
                bases=(o.ConfigurationSettings,))

            ConfigurationSetting.fix_up(o.ConfigurationSettings, self.settings)
            o.ConfigurationSettings.fix_up(o)
            Option.fix_up(o)
        else:
            raise TypeError('Incorrect usage: Configuration decorator applied to {0}'.format(type(o), o.__name__))

        return o 
Example #19
Source File: decorators.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, o):

        if isfunction(o):
            # We must wait to finalize configuration as the class containing this function is under construction
            # at the time this call to decorate a member function. This will be handled in the call to
            # o.ConfigurationSettings.fix_up(o) in the elif clause of this code block.
            o._settings = self.settings
        elif isclass(o):

            # Set command name

            name = o.__name__
            if name.endswith('Command'):
                name = name[:-len('Command')]
            o.name = six.text_type(name.lower())

            # Construct ConfigurationSettings instance for the command class

            o.ConfigurationSettings = ConfigurationSettingsType(
                module=o.__module__ + '.' + o.__name__,
                name='ConfigurationSettings',
                bases=(o.ConfigurationSettings,))

            ConfigurationSetting.fix_up(o.ConfigurationSettings, self.settings)
            o.ConfigurationSettings.fix_up(o)
            Option.fix_up(o)
        else:
            raise TypeError('Incorrect usage: Configuration decorator applied to {0}'.format(type(o), o.__name__))

        return o 
Example #20
Source File: decorator.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def decorator(caller, _func=None):
    """decorator(caller) converts a caller function into a decorator"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    defaultargs, defaults = '', ()
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
        nargs = caller.__code__.co_argcount
        ndefs = len(caller.__defaults__ or ())
        defaultargs = ', '.join(caller.__code__.co_varnames[nargs-ndefs:nargs])
        if defaultargs:
            defaultargs += ','
        defaults = caller.__defaults__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call=caller, _decorate_=decorate)
    dec = FunctionMaker.create(
        '%s(func, %s)' % (name, defaultargs),
        'if func is None: return lambda func:  _decorate_(func, _call, (%s))\n'
        'return _decorate_(func, _call, (%s))' % (defaultargs, defaultargs),
        evaldict, doc=doc, module=caller.__module__, __wrapped__=caller)
    if defaults:
        dec.__defaults__ = (None,) + defaults
    return dec


# ####################### contextmanager ####################### # 
Example #21
Source File: test_connection.py    From pylxd with Apache License 2.0 5 votes vote down vote up
def test_get_object(self, tag, effect, result, mg):
        mg.return_value.getresponse.return_value = FakeResponse(*effect)
        if inspect.isclass(result):
            self.assertRaises(result, self.conn.get_object)
        else:
            self.assertEqual(result, self.conn.get_object()) 
Example #22
Source File: decorators.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, o):

        if isfunction(o):
            # We must wait to finalize configuration as the class containing this function is under construction
            # at the time this call to decorate a member function. This will be handled in the call to
            # o.ConfigurationSettings.fix_up(o) in the elif clause of this code block.
            o._settings = self.settings
        elif isclass(o):

            # Set command name

            name = o.__name__
            if name.endswith('Command'):
                name = name[:-len('Command')]
            o.name = six.text_type(name.lower())

            # Construct ConfigurationSettings instance for the command class

            o.ConfigurationSettings = ConfigurationSettingsType(
                module=o.__module__ + '.' + o.__name__,
                name='ConfigurationSettings',
                bases=(o.ConfigurationSettings,))

            ConfigurationSetting.fix_up(o.ConfigurationSettings, self.settings)
            o.ConfigurationSettings.fix_up(o)
            Option.fix_up(o)
        else:
            raise TypeError('Incorrect usage: Configuration decorator applied to {0}'.format(type(o), o.__name__))

        return o 
Example #23
Source File: decorators.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, o):

        if isfunction(o):
            # We must wait to finalize configuration as the class containing this function is under construction
            # at the time this call to decorate a member function. This will be handled in the call to
            # o.ConfigurationSettings.fix_up(o) in the elif clause of this code block.
            o._settings = self.settings
        elif isclass(o):

            # Set command name

            name = o.__name__
            if name.endswith('Command'):
                name = name[:-len('Command')]
            o.name = six.text_type(name.lower())

            # Construct ConfigurationSettings instance for the command class

            o.ConfigurationSettings = ConfigurationSettingsType(
                module=o.__module__ + '.' + o.__name__,
                name='ConfigurationSettings',
                bases=(o.ConfigurationSettings,))

            ConfigurationSetting.fix_up(o.ConfigurationSettings, self.settings)
            o.ConfigurationSettings.fix_up(o)
            Option.fix_up(o)
        else:
            raise TypeError('Incorrect usage: Configuration decorator applied to {0}'.format(type(o), o.__name__))

        return o 
Example #24
Source File: didyoumean_internal.py    From DidYouMean-Python with MIT License 5 votes vote down vote up
def get_types_for_str_using_names(name, frame):
    """Get types corresponding to a string name using names in frame.

    This does not find everything as builtin types for instance may not
    be in the names.
    """
    return set(obj
               for obj, _ in get_objects_in_frame(frame).get(name, [])
               if inspect.isclass(obj) and obj.__name__ == name) 
Example #25
Source File: loadables.py    From zun with Apache License 2.0 5 votes vote down vote up
def _is_correct_class(self, obj):
        """Judge whether class type is correct

        Return whether an object is a class of the correct type and
        is not prefixed with an underscore.
        """
        return (inspect.isclass(obj) and
                (not obj.__name__.startswith('_')) and
                issubclass(obj, self.loadable_cls_type)) 
Example #26
Source File: register.py    From uplink with MIT License 5 votes vote down vote up
def register_converter_factory(self, proxy):
        factory = proxy() if inspect.isclass(proxy) else proxy
        if not isinstance(factory, interfaces.Factory):
            raise TypeError(
                "Failed to register '%s' as a converter factory: it is not an "
                "instance of '%s'." % (factory, interfaces.Factory)
            )
        self._register.appendleft(factory)
        return proxy 
Example #27
Source File: arguments.py    From uplink with MIT License 5 votes vote down vote up
def _process_annotation(self, name, annotation):
        if inspect.isclass(annotation):
            annotation = annotation()
        if isinstance(annotation, TypedArgument) and annotation.type is None:
            annotation.type = self._argument_types.pop(name, None)
        if isinstance(annotation, NamedArgument) and annotation.name is None:
            annotation.name = name
        return annotation 
Example #28
Source File: utils.py    From uplink with MIT License 5 votes vote down vote up
def is_subclass(cls, class_info):
    return inspect.isclass(cls) and issubclass(cls, class_info) 
Example #29
Source File: _extras.py    From uplink with MIT License 5 votes vote down vote up
def install(installable, _installers=_INSTALLERS):
    cls = installable if inspect.isclass(installable) else type(installable)
    for base_cls in _installers:
        if issubclass(cls, base_cls):
            _installers[base_cls](installable)
            break
    else:
        raise TypeError("Failed to install: '%s'" % str(installable))

    return installable 
Example #30
Source File: wrappers.py    From gist-alfred with MIT License 5 votes vote down vote up
def resolve_path(module, name):
    if isinstance(module, string_types):
        __import__(module)
        module = sys.modules[module]

    parent = module

    path = name.split('.')
    attribute = path[0]

    original = getattr(parent, attribute)
    for attribute in path[1:]:
        parent = original

        # We can't just always use getattr() because in doing
        # that on a class it will cause binding to occur which
        # will complicate things later and cause some things not
        # to work. For the case of a class we therefore access
        # the __dict__ directly. To cope though with the wrong
        # class being given to us, or a method being moved into
        # a base class, we need to walk the class hierarchy to
        # work out exactly which __dict__ the method was defined
        # in, as accessing it from __dict__ will fail if it was
        # not actually on the class given. Fallback to using
        # getattr() if we can't find it. If it truly doesn't
        # exist, then that will fail.

        if inspect.isclass(original):
            for cls in inspect.getmro(original):
                if attribute in vars(cls):
                    original = vars(cls)[attribute]
                    break
            else:
                original = getattr(original, attribute)

        else:
            original = getattr(original, attribute)

    return (parent, attribute, original)