Python inspect 模块,isclass() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.isclass()

项目:warriorframework    作者:warriorframework    | 项目源码 | 文件源码
def get_action(driver, keyword):
    """get action class corresponding to the keyword in the driver
    """
    drvmod = 'ProductDrivers.' + driver
    drvmodobj = importlib.import_module(drvmod)
    drvfile_methods = inspect.getmembers(drvmodobj, inspect.isroutine)
    main_method = [item[1] for item in drvfile_methods if item[0] == 'main'][0]
    main_src = inspect.getsource(main_method)
    pkglstmatch = re.search(r'package_list.*=.*\[(.*)\]', main_src, re.MULTILINE | re.DOTALL)
    pkglst = pkglstmatch.group(1).split(',')
    for pkg in pkglst:
        pkgobj = importlib.import_module(pkg)
        pkgdir = os.path.dirname(pkgobj.__file__)
        action_modules = [pkg+'.'+name for _, name, _ in pkgutil.iter_modules([pkgdir])]
        action_module_objs = [importlib.import_module(action_module) for action_module in action_modules]
        for action_module_obj in action_module_objs:
            for action_class in inspect.getmembers(action_module_obj, inspect.isclass):
                for func_name in inspect.getmembers(action_class[1], inspect.isroutine):
                    if keyword == func_name[0]:
                        return action_class[1]
    return None
项目:python-driver    作者:bblfsh    | 项目源码 | 文件源码
def get_containing_module(value):
    """
    Return the name of the module containing the given value, or
    C{None} if the module name can't be determined.
    @rtype: L{DottedName}
    """
    if inspect.ismodule(value):
        return DottedName(value.__name__)
    elif isclass(value):
        return DottedName(value.__module__)
    elif (inspect.ismethod(value) and value.im_self is not None and
          value.im_class is ClassType): # class method.
        return DottedName(value.im_self.__module__)
    elif inspect.ismethod(value):
        return DottedName(value.im_class.__module__)
    elif inspect.isroutine(value):
        module = _find_function_module(value)
        if module is None: return None
        return DottedName(module)
    else:
        return None
项目:estreamer    作者:spohara79    | 项目源码 | 文件源码
def __init__(self, type_list):
        mod_name = sys.modules[__name__]
        cls_list = [
            cls[0]
            for cls in inspect.getmembers(mod_name)
            if cls[0].isupper() and inspect.isclass(cls[1]) and cls[1].__module__ == __name__
        ]
        try:
            type_list.remove('TERMINATE') # can't hold order, so remove it and add it back when done
        except ValueError as exc:
            pass
        type_list = list(set(type_list).intersection(set(cls_list))) # remove bad and duplicate values
        array_args = [
            {'version': getattr(getattr(mod_name, rtype), 'version'), 
            'code': getattr(getattr(mod_name, rtype), 'code')}
            for rtype in type_list
        ]
        array_args.append({'code': 0, 'version': 0}) # add TERMINATE as last req
        self.streaming_event_request = StreamingEventRequest(service_array=array_args, timestamp=Struct.get_ts(), flags=Struct.get_flags())
        self.message_header = MessageHeader(type=2049, data=self.streaming_event_request)
    self.record = self.message_header.pack()
项目:plugs-mail    作者:solocompt    | 项目源码 | 文件源码
def get_plugs_mail_classes(self, app):
        """
        Returns a list of tuples, but it should
        return a list of dicts
        """
        classes = []
        members = self.get_members(app)
        for member in members:
            name, cls = member
            if inspect.isclass(cls) and issubclass(cls, PlugsMail) and name != 'PlugsMail':
                files_ = self.get_template_files(app.__file__, name)
                for file_ in files_:
                    try:
                        description = cls.description
                        location = file_
                        language = self.get_template_language(location)
                        classes.append((name, location, description, language))
                    except AttributeError:
                        raise AttributeError('Email class must specify email description.')
        return classes
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __new__(cls, name, bases, attrs):
        new_class = super(AliasType, cls).__new__(cls, name, bases, attrs)

        # see whether we've got an Alias inner class:
        if inspect.isclass(attrs.get('Alias', None)):
            alias = attrs['Alias']
            setattr(new_class, '__aliases', {})
            for attr, value in alias.__dict__.items():
                # don't want any "private" attrs appearing
                if attr.startswith('_'):
                    continue
                # don't care if these aren't tuples or lists
                if not isinstance(value, (tuple, list)):
                    continue
                # no point in setting up an alias for something which isn't a
                # class attribute:
                if not attr in attrs:
                    continue

                # if we've got to here put the lookups into the __aliases dict:
                for key in value:
                    new_class.__dict__['__aliases'][key] = attr
                    setattr(new_class, key, AliasDescriptor(key))

        return new_class
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def describe(module):
   """ Describe the module object passed as argument
   including its classes and functions """

   wi('[Module: %s]\n' % module.__name__)

   indent()

   count = 0

   for name in dir(module):
       obj = getattr(module, name)
       if inspect.isclass(obj):
          count += 1; describe_klass(obj)
       elif (inspect.ismethod(obj) or inspect.isfunction(obj)):
          count +=1 ; describe_func(obj)
       elif inspect.isbuiltin(obj):
          count += 1; describe_builtin(obj)

   if count==0:
      wi('(No members)')

   dedent()
项目:functest    作者:opnfv    | 项目源码 | 文件源码
def init_db():
    """
    Import all modules here that might define models so that
    they will be registered properly on the metadata, and then
    create a database
    """
    def func(subcls):
        """ To check the subclasses of BASE"""
        try:
            if issubclass(subcls[1], BASE):
                return True
        except TypeError:
            pass
        return False
    # pylint: disable=bad-builtin
    subclses = filter(func, inspect.getmembers(models, inspect.isclass))
    LOGGER.debug('Import models: %s', [subcls[1] for subcls in subclses])
    BASE.metadata.create_all(bind=ENGINE)
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def register_check(check, codes=None):
    """Register a new check object."""
    def _add_check(check, kind, codes, args):
        if check in _checks[kind]:
            _checks[kind][check][0].extend(codes or [])
        else:
            _checks[kind][check] = (codes or [''], args)
    if inspect.isfunction(check):
        args = _get_parameters(check)
        if args and args[0] in ('physical_line', 'logical_line'):
            if codes is None:
                codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
            _add_check(check, args[0], codes, args)
    elif inspect.isclass(check):
        if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
            _add_check(check, 'tree', codes, None)
项目:deep-prior    作者:moberweger    | 项目源码 | 文件源码
def activation_str(self):
        """
        Get printable string from activation function.
        :return: string
        """
        if hasattr(self, 'activation'):
            if self.activation is None:
                return str(None)
            elif inspect.isclass(self.activation):
                return self.activation.__class__.__name__
            elif inspect.isfunction(self.activation):
                return self.activation.__name__
            else:
                return str(self.activation)
        else:
            return ''
项目:mycroft-light    作者:MatthewScholefield    | 项目源码 | 文件源码
def load_skill_class(self, folder_name):
        cls_name = to_camel(folder_name)
        skill_name = folder_name.replace(self._suffix, '')

        if skill_name in self._classes:
            self.rt.intent.remove_skill(skill_name)

        try:
            mod = import_module(folder_name + '.skill')
            mod = reload(mod)
            cls = getattr(mod, cls_name, '')
        except:
            log.exception('Loading', folder_name)
            return None

        if not isclass(cls):
            log.warning('Could not find', cls_name, 'in', folder_name)
            return None

        return cls
项目:mycroft-light    作者:MatthewScholefield    | 项目源码 | 文件源码
def load_class(self, option):
        package = self._package + '.' + option + self._suffix
        try:
            mod = import_module(package)
            cls = getattr(mod, to_camel(option + self._suffix), '')
            if not isclass(cls):
                log.error('Class not callable:', cls)
            else:
                if hasattr(self, 'plugin_path'):
                    plugin_path = self.plugin_path + '.'
                else:
                    plugin_path = ''

                cls.attr_name = self.make_name(cls)
                cls.plugin_path = plugin_path + cls.attr_name
                return cls
        except:
            log.exception('Loading Module', package)
        return None
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def _registered(self, cls):
        if inspect.isclass(cls) and issubclass(cls, self._registerable_class):
            found = self._registry.get(cls, None)
            if found:
                return found
        else:
            # Allow for fetching by slugs as well.
            for registered in self._registry.values():
                if registered.slug == cls:
                    return registered
        class_name = self._registerable_class.__name__
        if hasattr(self, "_registered_with"):
            parent = self._registered_with._registerable_class.__name__
            raise NotRegistered('%(type)s with slug "%(slug)s" is not '
                                'registered with %(parent)s "%(name)s".'
                                % {"type": class_name,
                                   "slug": cls,
                                   "parent": parent,
                                   "name": self.slug})
        else:
            slug = getattr(cls, "slug", cls)
            raise NotRegistered('%(type)s with slug "%(slug)s" is not '
                                'registered.' % {"type": class_name,
                                                 "slug": slug})
项目:zoocore    作者:dsparrow27    | 项目源码 | 文件源码
def registerByPackage(self, pkg):
        """This function is similar to registerByModule() but works on packages, this is an expensive operation as it
        requires a recursive search by importing all sub modules and and searching them.

        :param pkg: The package path to register eg. zoo.libs.apps
        :type pkg: str
        """
        mod = modules.importModule(pkg)
        realPath = os.path.dirname(inspect.getfile(mod))
        pkgSplitPath = pkg.replace(".", os.path.sep)
        self.basePaths.append(realPath)

        for subModule in modules.iterModules(realPath):
            filename = os.path.splitext(os.path.basename(subModule))[0]
            if filename.startswith("__") or subModule.endswith(".pyc"):
                continue
            newDottedPath = pkg + subModule.split(pkgSplitPath)[-1].replace(os.path.sep, ".").split(".py")[0]
            subModuleObj = modules.importModule(newDottedPath)
            for member in modules.iterMembers(subModuleObj, predicate=inspect.isclass):
                self.registerPlugin(member[1])
项目:zoocore    作者:dsparrow27    | 项目源码 | 文件源码
def registerByPackage( pkg):
    """This function is similar to registerByModule() but works on packages, this is an expensive operation as it
    requires a recursive search by importing all sub modules and and searching them.

    :param pkg: The package path to register eg. zoo.libs.apps
    :type pkg: str
    """
    visited = set()
    commands = []
    for subModule in modules.iterModules(pkg):
        filename = os.path.splitext(os.path.basename(subModule))[0]
        if filename.startswith("__") or subModule.endswith(".pyc") or filename in visited:
            continue
        visited.add(filename)
        subModuleObj = modules.importModule(subModule)
        for member in modules.iterMembers(subModuleObj, predicate=inspect.isclass):
            newCom = registerCommand(member[1])
            if newCom:
                commands.append(newCom)
    return commands
项目:ronin    作者:tliron    | 项目源码 | 文件源码
def apply(self):
        """
        Applies all extensions and hooks to this phase.
        """

        def apply_extensions(extensions):
            for extension in extensions:
                verify_type_or_subclass(extension, Extension)
                if isclass(extension):
                    extension = extension()
                extension.apply_to_phase(self)
                apply_extensions(extension.extensions)

        apply_extensions(self.extensions)

        for hook in self.hooks:
            hook(self)
项目:ronin    作者:tliron    | 项目源码 | 文件源码
def command_as_str(self, argument_filter=None):
        """
        Applies all extensions to the executor and calls its ``command_as_str``.

        :returns: command as string
        :rtype: basestring
        """

        def apply_extensions(extensions):
            for extension in extensions:
                verify_type_or_subclass(extension, Extension)
                if isclass(extension):
                    extension = extension()
                extension.apply_to_executor(self.executor)
                apply_extensions(extension.extensions)

        apply_extensions(self.extensions)

        return self.executor.command_as_str(argument_filter)
项目:ronin    作者:tliron    | 项目源码 | 文件源码
def verify_type(value, the_type):
    """
    Raises :class:`TypeError` if the value is not an instance of the type.

    :param value: value
    :param the_type: type or type name
    :type the_type: type|basestring
    :raises TypeError: if ``value`` is not an instance of ``the_type``
    :raises ~exceptions.ValueError: if ``the_type`` is invalid
    :raises ImportError: if could not import the module
    :raises AttributeError: if could not find the symbol in the module
    """

    if isinstance(the_type, basestring):
        the_type = import_symbol(the_type)
        if not isclass(the_type):
            raise ValueError(u'{} is not a type'.format(the_type))

    if not isinstance(value, the_type):
        raise TypeError(u'not an instance of {}: {}'.format(type_name(the_type),
                                                            type_name(type(value))))
项目:ronin    作者:tliron    | 项目源码 | 文件源码
def verify_subclass(value, the_type):
    """
    Raises :class:`TypeError` if the value is not a subclass of the type.

    :param value: value
    :param the_type: type or type name
    :type the_type: type|basestring
    :raises TypeError: if ``value`` is not a subclass of ``the_type``
    :raises ~exceptions.ValueError: if ``the_type`` is invalid
    :raises ImportError: if could not import the module
    :raises AttributeError: if could not find the symbol in the module
    """

    if isinstance(the_type, basestring):
        the_type = import_symbol(the_type)
        if not isclass(the_type):
            raise ValueError(u'{} is not a type'.format(the_type))

    if not issubclass(value, the_type):
        raise TypeError(u'not a subclass of {}: {}'.format(type_name(the_type),
                                                           type_name(type(value))))
项目:bothub-sdk-python    作者:bothub-studio    | 项目源码 | 文件源码
def get_decorators(cls):
    decorators = {}

    def visit_FunctionDef(node):
        decorators[node.name] = []
        for n in node.decorator_list:
            name = ''
            if isinstance(n, ast.Call):
                name = n.func.attr if isinstance(n.func, ast.Attribute) else n.func.id
            else:
                name = n.attr if isinstance(n, ast.Attribute) else n.id

            args = [a.s for a in n.args] if hasattr(n, 'args') else []
            decorators[node.name].append((name, args))

    node_iter = ast.NodeVisitor()
    node_iter.visit_FunctionDef = visit_FunctionDef
    _cls = cls if inspect.isclass(cls) else cls.__class__
    node_iter.visit(ast.parse(inspect.getsource(_cls)))
    return decorators
项目:trio2o    作者:openstack    | 项目源码 | 文件源码
def test_resources(self):
        """Create all the resources to test model definition"""
        try:
            model_list = []
            for _, model_class in inspect.getmembers(models):
                if inspect.isclass(model_class) and (
                        issubclass(model_class, core.ModelBase)):
                    model_list.append(model_class)
            for model_class in _sort_model_by_foreign_key(model_list):
                create_dict = _construct_resource_dict(model_class)
                with self.context.session.begin():
                    core.create_resource(
                        self.context, model_class, create_dict)
        except Exception as e:
            msg = str(e)
            self.fail('test_resources raised Exception unexpectedly %s' % msg)
项目:harbour-mercury    作者:chstem    | 项目源码 | 文件源码
def join(self, dest, join_type=None, on=None):
        src = self._query_ctx
        if on is None:
            require_join_condition = join_type != JOIN.CROSS and (
                isinstance(dest, SelectQuery) or
                (isclass(dest) and not src._meta.rel_exists(dest)))
            if require_join_condition:
                raise ValueError('A join condition must be specified.')
        elif join_type == JOIN.CROSS:
            raise ValueError('A CROSS join cannot have a constraint.')
        elif isinstance(on, basestring):
            on = src._meta.fields[on]
        self._joins.setdefault(src, [])
        self._joins[src].append(Join(src, dest, join_type, on))
        if not isinstance(dest, SelectQuery):
            self._query_ctx = dest
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def __init__(self, base=ServiceSOAPBinding, prefix='soap',
                 service_class=SOAPService):
        '''
        parameters:
            base -- either a class definition, or a str representing a qualified
                class name (eg. module.name.classname)
            prefix -- method prefix.
        '''
        if inspect.isclass(base):
            self.base_class_name = base.__name__
            self.base_module_name = inspect.getmodule(base).__name__
        else:
            self.base_module_name, self.base_class_name  = base.rsplit('.', 1)

        self.wsdl = None
        self.method_prefix = prefix
        self._service_class = SOAPService

        self.header  = None
        self.imports  = None
        self.messages = []
        self._services = None
        self.types_module_path = None
        self.types_module_name = None
        self.messages_module_name = None
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _list_xml_members(cls):
    """Generator listing all members which are XML elements or attributes.

    The following members would be considered XML members:
    foo = 'abc' - indicates an XML attribute with the qname abc
    foo = SomeElement - indicates an XML child element
    foo = [AnElement] - indicates a repeating XML child element, each instance
        will be stored in a list in this member
    foo = ('att1', '{http://example.com/namespace}att2') - indicates an XML
        attribute which has different parsing rules in different versions of
        the protocol. Version 1 of the XML parsing rules will look for an
        attribute with the qname 'att1' but verion 2 of the parsing rules will
        look for a namespaced attribute with the local name of 'att2' and an
        XML namespace of 'http://example.com/namespace'.
    """
    members = []
    for pair in inspect.getmembers(cls):
      if not pair[0].startswith('_') and pair[0] != 'text':
        member_type = pair[1]
        if (isinstance(member_type, tuple) or isinstance(member_type, list)
            or isinstance(member_type, (str, unicode))
            or (inspect.isclass(member_type)
                and issubclass(member_type, XmlElement))):
          members.append(pair)
    return members
项目:auger    作者:laffra    | 项目源码 | 文件源码
def get_defining_item(self, code):
        for modname, mod in sys.modules.iteritems():
            file = getattr(mod, '__file__', '').replace('.pyc', '.py')
            if file == code.co_filename:
                for classname,clazz in inspect.getmembers(mod, predicate=inspect.isclass):
                    for name,member in inspect.getmembers(clazz, predicate=inspect.ismethod):
                        filename = member.im_func.func_code.co_filename
                        lineno = member.im_func.func_code.co_firstlineno
                        if filename == code.co_filename and lineno == code.co_firstlineno:
                            self.imports_.add((modname, clazz.__name__))
                            return clazz, member
                    for name,member in inspect.getmembers(clazz, predicate=inspect.isfunction):
                        filename = member.func_code.co_filename
                        lineno = member.func_code.co_firstlineno
                        if filename == code.co_filename and lineno == code.co_firstlineno:
                            self.imports_.add((modname, clazz.__name__))
                            return clazz, member
                self.imports_.add((modname,))
                return mod, mod
项目:SiteFab    作者:ebursztein    | 项目源码 | 文件源码
def __init__(self, renderer=None, inline=None, block=None, **kwargs):
        if not renderer:
            renderer = Renderer(**kwargs)
        else:
            kwargs.update(renderer.options)

        self.renderer = renderer

        if inline and inspect.isclass(inline):
            inline = inline(renderer, **kwargs)
        if block and inspect.isclass(block):
            block = block(**kwargs)

        if inline:
            self.inline = inline
        else:
            self.inline = InlineLexer(renderer, **kwargs)

        self.block = block or BlockLexer(BlockGrammar())
        self.footnotes = []
        self.tokens = []

        # detect if it should parse text in block html
        self._parse_block_html = kwargs.get('parse_block_html')
项目:palladio    作者:slipguru    | 项目源码 | 文件源码
def get_doc_object(obj, what=None, config=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=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, '', config=config)
    else:
        return SphinxDocString(pydoc.getdoc(obj), config=config)
项目:palladio    作者:slipguru    | 项目源码 | 文件源码
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 callable(obj):
            what = 'function'
        else:
            what = 'object'
    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)
项目:palladio    作者:slipguru    | 项目源码 | 文件源码
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):
            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)]
项目:microcosm-flask    作者:globality-corp    | 项目源码 | 文件源码
def name_for(obj):
    """
    Get a name for something.

    Allows overriding of default names using the `__alias__` attribute.

    """
    if isinstance(obj, string_types):
        return obj

    cls = obj if isclass(obj) else obj.__class__

    if hasattr(cls, "__alias__"):
        return underscore(cls.__alias__)
    else:
        return underscore(cls.__name__)
项目:python-miio    作者:rytilahti    | 项目源码 | 文件源码
def check_and_create_device(self, info, addr) -> Optional[Device]:
        """Create a corresponding :class:`Device` implementation
         for a given info and address.."""
        name = info.name
        for identifier, v in DEVICE_MAP.items():
            if name.startswith(identifier):
                if inspect.isclass(v):
                    _LOGGER.debug("Found a supported '%s', using '%s' class",
                                  name, v.__name__)
                    return create_device(addr, v)
                elif callable(v):
                    dev = Device(ip=addr)
                    _LOGGER.info("%s: token: %s",
                                 v(info),
                                 pretty_token(dev.do_discover().checksum))
                    return None
        _LOGGER.warning("Found unsupported device %s at %s, "
                        "please report to developers", name, addr)
        return None
项目:whatsapp-rest-webservice    作者:svub    | 项目源码 | 文件源码
def _construct(self):
        logger.debug("Initializing stack")
        for s in self.__stack:
            if type(s) is tuple:
                logger.warn("Implicit declaration of parallel layers in a tuple is deprecated, pass a YowParallelLayer instead")
                inst = YowParallelLayer(s)
            else:
                if inspect.isclass(s):
                    if issubclass(s, YowLayer):
                        inst = s()
                    else:
                        raise ValueError("Stack must contain only subclasses of YowLayer")
                elif issubclass(s.__class__, YowLayer):
                        inst = s
                else:
                    raise ValueError("Stack must contain only subclasses of YowLayer")
                #inst = s()
            logger.debug("Constructed %s" % inst)
            inst.setStack(self)
            self.__stackInstances.append(inst)

        for i in range(0, len(self.__stackInstances)):
            upperLayer = self.__stackInstances[i + 1] if (i + 1) < len(self.__stackInstances) else None
            lowerLayer = self.__stackInstances[i - 1] if i > 0 else None
            self.__stackInstances[i].setLayers(upperLayer, lowerLayer)
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
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 callable(obj):
            what = 'function'
        else:
            what = 'object'
    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)
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
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)]
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
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
        (not hasattr(obj, '__init__') or
        '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, ''
项目:evolution    作者:tanchao90    | 项目源码 | 文件源码
def _toStardardCondition(condition):
    '''?????????????????'''

    if inspect.isclass(condition):
        return lambda x: isinstance(x, condition)

    if isinstance(condition, (tuple, list)):
        cls, condition = condition[:2]
        if condition is None:
            return _toStardardCondition(cls)

        if cls in (str, unicode) and condition[0] == condition[-1] == '/':
            return lambda x: (isinstance(x, cls)
                              and re.match(condition[1:-1], x) is not None)

        return lambda x: isinstance(x, cls) and eval(condition)

    return condition
项目:evolution    作者:tanchao90    | 项目源码 | 文件源码
def _toStardardCondition(condition):
    '''?????????????????'''

    # class condition
    if inspect.isclass(condition):
        info = "must be %s type" % condition.__name__
        return lambda x: isinstance(x, condition) or info

    if isinstance(condition, (tuple, list)):
        cls, condition = condition[:2]
        if condition is None:
            return _toStardardCondition(cls)

        # regular condition
        if cls in (str, unicode) and condition[0] == condition[-1] == '/':
            info = 'must match regular expression: %s' % condition
            return lambda x: (isinstance(x, cls) and re.match(condition[1:-1], x) is not None) or info

        # pure str condition
        info = 'must satisfy rule: %s' % condition
        return lambda x: (isinstance(x, cls) and eval(condition)) or info

    # fcuntion condition
    return condition
项目:simLAB    作者:kamwar    | 项目源码 | 文件源码
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
项目:pychinadns    作者:faicker    | 项目源码 | 文件源码
def check_handler(value):
    h = None
    HANDLER_PREFIX = "handler_"
    name = HANDLER_PREFIX + "base"
    base_mod = load_mod(PKG_NAME, name)
    if not base_mod:
        print("load module %s failed" % (name), file=sys.stderr)
        sys.exit(1)
    try:
        base_cls = getattr(base_mod, "HandlerBase")
    except AttributeError as e:
        print("err=%s, can't find HandlerBase class" % (e), file=sys.stderr)
        sys.exit(1)

    name = HANDLER_PREFIX + value
    mod = load_mod(PKG_NAME, name)
    if not mod:
        print("load module %s failed" % (name), file=sys.stderr)
        sys.exit(1)
    for v in dir(mod):
        cls = getattr(mod, v)
        if inspect.isclass(cls) and issubclass(cls, base_cls):
            return cls()
    if h is None:
        raise argparse.ArgumentTypeError("%s is an invalid handler" % value)
项目:python-gamelocker    作者:schneefux    | 项目源码 | 文件源码
def modulemap():
    """Returns a dictionary where `type_name`s are mapped
       to corresponding classes from `gamelocker.datatypes`.

    :return: A dictionary with keys of `type_name`
             and values of :class:`DataMessage` subclasses.
    :rtype: :class:`gamelocker.janus.DataMessage`
    """
    typemap = dict()
    classes = inspect.getmembers(sys.modules[__name__], inspect.isclass)
    for name, value in classes:
        if name == "Attribute" or name == "DataMessage":
            continue
        typemap[value.type_name] = value

    return typemap
项目:pyShadowsocks    作者:FTwOoO    | 项目源码 | 文件源码
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__)
项目:crawlers    作者:pyjobs    | 项目源码 | 文件源码
def get_spider_class(spider_name, spiders_directory=None):
    spider_class = None

    spider_module_name = get_spider_module_name(spider_name)

    if spider_module_name in get_spiders_modules_names(spiders_directory):
        spider_module = import_module(spider_module_name)
        for module_attribute_name in dir(spider_module):
            module_attribute = getattr(spider_module, module_attribute_name)
            if inspect.isclass(module_attribute) \
                    and module_attribute is not JobSpider \
                    and issubclass(module_attribute, JobSpider):
                spider_class = module_attribute
                break

    return spider_class
项目:Dallinger    作者:Dallinger    | 项目源码 | 文件源码
def load():
    """Load the active experiment."""
    if os.getcwd() not in sys.path:
        sys.path.append(os.getcwd())

    try:
        exp = imp.load_source('dallinger_experiment', "dallinger_experiment.py")
        classes = inspect.getmembers(exp, inspect.isclass)
        exps = [c for c in classes
                if (c[1].__bases__[0].__name__ in "Experiment")]
        this_experiment = exps[0][0]
        mod = __import__('dallinger_experiment', fromlist=[this_experiment])
        return getattr(mod, this_experiment)

    except ImportError:
        logger.error('Could not import experiment.')
        raise