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

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

项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def __init__(self, name, bases, classdict):
        type.__init__(self, name, bases, classdict)
        spd_file = classdict.get('SPD_FILE', None)
        if spd_file:
            # Get the module that contains the test case class. This allows us
            # to find the SPD file relative to its location.
            module = inspect.getmodule(self)
            module_path = os.path.dirname(module.__file__)
            spd_path = os.path.normpath(os.path.join(module_path, spd_file))

            # Parse the SPD to get the implementation IDs.
            spd = SPDParser.parse(spd_path)
            self.__impls__ = [impl.get_id() for impl in spd.get_implementation()]

            # Update the path to the SPD file.
            self.spd_file = spd_path
        else:
            self.spd_file = None
            self.__impls__ = ()
项目: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")
项目:abusehelper    作者:Exploit-install    | 项目源码 | 文件源码
def format_type(value):
    """
    Return a full name of the value's type.

    >>> import abusehelper.core.events
    >>> format_type(abusehelper.core.events.Event())
    'abusehelper.core.events.Event'

    The package path prefix for builtin types gets omitted.

    >>> format_type(abusehelper.core.events)
    'module'
    >>> format_type(abusehelper.core.events.Event)
    'type'
    >>> format_type(1)
    'int'
    """

    type_ = type(value)
    name = type_.__name__
    module = inspect.getmodule(type_)
    if module is not None and module.__name__ != "__builtin__":
        name = module.__name__ + "." + name
    return 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.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 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
项目: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)
项目: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
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def setUpInitDef(self, service):
        '''set __init__ function
        '''
        assert isinstance(service, WSDLTools.Service), \
            'expecting WSDLTools.Service instance.'

        sd = self._services[service.name]
        d = sd.initdef

        if sd.location is not None:
            _,_,path,_,_,_ = urlparse.urlparse(sd.location)
            print >>d, '%sdef __init__(self, post=\'%s\', **kw):' %(self.getIndent(level=1), path)
        else:
            print >>d, '%sdef __init__(self, post, **kw):' %self.getIndent(level=1)

        # Require POST initialization value for test implementation
        if self.base_module_name == inspect.getmodule(ServiceSOAPBinding).__name__:
            print >>d, '%s%s.__init__(self, post)' %(self.getIndent(level=2), self.base_class_name)
            return

        # No POST initialization value, obtained from HTTP Request in twisted or wsgi
        print >>d, '%s%s.__init__(self)' %(self.getIndent(level=2), self.base_class_name)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def debug(self, message):
        if not self.opts['_debug']:
            return
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("DEBUG", message, modName)
        return
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def alias(name, class_object):
    """
    Create an alias of a class object

    The objective of this method is to have
    an alias that is Registered. i.e If we have

        class_b = class_a

    Makes `class_b` an alias of `class_a`, but if
    `class_a` is registered by its metaclass,
    `class_b` is not. The solution

        alias('class_b', class_a)

    is equivalent to:

        class_b = class_a
        Register['class_b'] = class_a
    """
    module = inspect.getmodule(class_object)
    module.__dict__[name] = class_object
    if isinstance(class_object, Registry):
        Registry[name] = class_object
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
def handle_method(method, method_name, class_name):
    method_errors = []

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

    docstring = inspect.getdoc(method)
    if docstring is None:
        method_errors.append((class_name, method_name,
                              '**missing** method-level docstring'))
    else:
        method_errors = [
            (class_name, method_name, e) for e in
            NumpyFunctionDocString(docstring, method).get_errors()
        ]
    return method_errors
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
def handle_class(val, class_name):
    cls_errors = []
    docstring = inspect.getdoc(val)
    if docstring is None:
        cls_errors.append((class_name,
                           '**missing** class-level docstring'))
    else:
        cls_errors = [
            (e,) for e in
            NumpyClassDocString(docstring, class_name, val).get_errors()
        ]
        # Get public methods and parse their docstrings
        methods = dict(((name, func) for name, func in inspect.getmembers(val)
                        if not name.startswith('_') and callable(func) and
                        type(func) is not type))
        for m_name, method in six.iteritems(methods):
            # skip error check if the method was inherited
            # from a parent class (which means it wasn't
            # defined in this source file)
            if inspect.getmodule(method) is not None:
                continue
            cls_errors.extend(handle_method(method, m_name, class_name))
    return cls_errors
项目: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
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def info(self, message):
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            if mod.__name__ == "sflib":
                frm = inspect.stack()[2]
                mod = inspect.getmodule(frm[0])
                if mod is None:
                    modName = "Unknown"
                else:
                    modName = mod.__name__
            else:
                modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("INFO", message, modName)
        return
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def debug(self, message):
        if not self.opts['_debug']:
            return
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            if mod.__name__ == "sflib":
                frm = inspect.stack()[2]
                mod = inspect.getmodule(frm[0])
                if mod is None:
                    modName = "Unknown"
                else:
                    modName = mod.__name__
            else:
                modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("DEBUG", message, modName)
        return
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_') or name == 'p_error':
                continue
            if isinstance(item, (types.FunctionType, types.MethodType)):
                line = item.__code__.co_firstlineno
                module = inspect.getmodule(item)
                p_functions.append((line, module, name, item.__doc__))

        # Sort all of the actions by line number; make sure to stringify
        # modules to make them sortable, since `line` may not uniquely sort all
        # p functions
        p_functions.sort(key=lambda p_function: (
            p_function[0],
            str(p_function[1]),
            p_function[2],
            p_function[3]))
        self.pfuncs = p_functions

    # Validate all of the p_functions
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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")
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
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")
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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")
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True
项目:sahriswiki    作者:prologic    | 项目源码 | 文件源码
def loadMacros():
    path = os.path.abspath(os.path.dirname(__file__))
    p = lambda x: os.path.splitext(x)[1] == ".py"
    modules = [x for x in os.listdir(path) if p(x) and not x == "__init__.py"]

    macros = {}

    for module in modules:
        name, _ = os.path.splitext(module)

        moduleName = "%s.%s" % (__package__, name)
        m = __import__(moduleName, globals(), locals(), __package__)

        p = lambda x: isfunction(x) and getmodule(x) is m
        for name, function in getmembers(m, p):
            name = name.replace("_", "-")
            try:
                macros[name] = function
            except Exception, e:
                continue

    return macros
项目:pydecor    作者:mplanchard    | 项目源码 | 文件源码
def log_call(decorated, logger=None, level='info',
             format_str=LOG_CALL_FMT_STR):
    """Log the parameters & results of a function call

    Designed to be called via the ``after`` decorator with
    ``pass_params=True`` and ``pass_decorated=True``. Use
    :any:`decorators.log_call` for easiest invocation.

    :param Decorated decorated: decorated function information
    :param Optional[logging.Logger] logger: optional logger instance
    :param Optional[str] level: log level - must be an acceptable Python
        log level, case-insensitive
    :param format_str: the string to use when formatting the results
    """
    if logger is None:
        name = getmodule(decorated.wrapped).__name__
        logger = getLogger(name)
    log_fn = getattr(logger, level.lower())
    msg = format_str.format(
        name=decorated.wrapped.__name__,
        args=decorated.args,
        kwargs=decorated.kwargs,
        result=decorated.result
    )
    log_fn(msg)
项目:django-schemas    作者:ryannjohnson    | 项目源码 | 文件源码
def get_class_that_defined_method(meth):
    """Returns the class that created the given method.

    A helper function for finding class methods amongst a list of many
    methods. 

    Source:
        http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545
    """
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
           if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__ # fallback to __qualname__ parsing
    if inspect.isfunction(meth):

        # Check to make sure the method has a "qualname"
        if not getattr(meth, '__qualname__', None):
            return None

        cls = getattr(inspect.getmodule(meth),
                      meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
        if isinstance(cls, type):
            return cls
    return None # not required since None would have been implicitly returned anyway
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def makeTest(self, obj, parent):
        """Look for doctests in the given object, which will be a
        function, method or class.
        """
        #print 'Plugin analyzing:', obj, parent  # dbg
        # always use whitespace and ellipsis options
        optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS

        doctests = self.finder.find(obj, module=getmodule(parent))
        if doctests:
            for test in doctests:
                if len(test.examples) == 0:
                    continue

                yield DocTestCase(test, obj=obj,
                                  optionflags=optionflags,
                                  checker=self.checker)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
        renderer=None):
    """Render text documentation, given an object or a path to an object."""
    if renderer is None:
        renderer = text
    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 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' + renderer.document(object, name)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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.__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")
项目:pytypes    作者:Stewori    | 项目源码 | 文件源码
def get_class_that_defined_method(meth):
    """Determines the class owning the given method.
    """
    if is_classmethod(meth):
        return meth.__self__
    if hasattr(meth, 'im_class'):
        return meth.im_class
    elif hasattr(meth, '__qualname__'):
        # Python 3
        try:
            cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
            cls = inspect.getmodule(meth)
            for cls_name in cls_names:
                cls = getattr(cls, cls_name)
            if isinstance(cls, type):
                return cls
        except AttributeError:
            # If this was called from a decorator and meth is not a method, this
            # can result in AttributeError, because at decorator-time meth has not
            # yet been added to module. If it's really a method, its class would be
            # already in, so no problem in that case.
            pass
    raise ValueError(str(meth)+' is not a method.')
项目:pytypes    作者:Stewori    | 项目源码 | 文件源码
def getmodule(code):
    """More robust variant of inspect.getmodule.
    E.g. has less issues on Jython.
    """
    try:
        md = inspect.getmodule(code, code.co_filename)
    except AttributeError:
        return inspect.getmodule(code)
    if md is None:
        # Jython-specific:
        # This is currently just a crutch; todo: resolve __pyclasspath__ properly!
        cfname = code.co_filename.replace('__pyclasspath__',
                os.path.realpath('')+os.sep+'__pyclasspath__')
        cfname = cfname.replace('$py.class', '.py')
        md = inspect.getmodule(code, cfname)
    if md is None:
        md = inspect.getmodule(code)
    return md
项目:pytypes    作者:Stewori    | 项目源码 | 文件源码
def get_callable_fq_for_code(code, locals_dict = None):
    """Determines the function belonging to a given code object in a fully qualified fashion.
    Returns a tuple consisting of
    - the callable
    - a list of classes and inner classes, locating the callable (like a fully qualified name)
    - the corresponding self object, if the callable is a method
    """
    if code in _code_callable_dict:
        res = _code_callable_dict[code]
        if not res[0] is None or locals_dict is None:
            return res
    md = getmodule(code)
    if not md is None:
        nesting = []
        res, slf = _get_callable_fq_for_code(code, md, md, False, nesting, set())
        if res is None and not locals_dict is None:
            nesting = []
            res, slf = _get_callable_from_locals(code, locals_dict, md, False, nesting)
        else:
            _code_callable_dict[code] = (res, nesting, slf)
        return res, nesting, slf
    else:
        return None, None, None
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
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")
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
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")
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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")
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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")
项目:highway.py    作者:PhilipTrauner    | 项目源码 | 文件源码
def print_out(message, color, file):
    stack_ = stack()
    # Interestingly the if statement below is not executed when excepting KeyboardInterrupts. Weird.
    # To prevent a crash we assume the module's name is 'Unknown'
    module = "Unknown"
    if getmodule(stack_[2][0]) == None:
        for i in stack_[2:]:
            if getmodule(i[0]) != None:
                try:
                    module = CACHED_MODULES[i[0].f_code]
                except KeyError:
                    module = getmodule(i[0]).__name__
                    CACHED_MODULES[i[0].f_code] = module
    else:
        try:
            module = CACHED_MODULES[stack_[2][0].f_code]
        except KeyError:
            module = getmodule(stack_[2][0]).__name__
            CACHED_MODULES[stack_[2][0].f_code] = module
    print("\033[32m%s\033[0m:%i ? %s%s\033[0m" % (
        module, stack_[2][0].f_lineno, color, 
        message), file=file)
    file.flush()
项目:sslstrip-hsts-openwrt    作者: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")
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者: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)
项目:Flask-NvRay-Blog    作者:rui7157    | 项目源码 | 文件源码
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")
项目:NeuroMobile    作者:AndrewADykman    | 项目源码 | 文件源码
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")
项目:packetweaver    作者:ANSSI-FR    | 项目源码 | 文件源码
def get_ability_instance_by_name(self, name, module_factory):
        # First, we reload the ability, just in case it changed on disk
        for abl in self._mod.exported_abilities:
            if abl.get_name() == name:
                reload(inspect.getmodule(abl))
        # We need to reload the "module" because the submodule were reloaded too
        self._mod = module_factory.reload_module(self._mod_path)

        for abl in self._mod.exported_abilities:
            if abl.get_name() == name:
                opts = {k: v for k, v in self._defaults.items() if k in abl.get_option_list()}
                return abl(
                    module_factory,
                    default_opts=opts,
                    view=self._view
                )
        return None
项目:esper    作者:scanner-research    | 项目源码 | 文件源码
def query(name):
    frame = inspect.stack()[1]
    module = inspect.getmodule(frame[0])
    filename = module.__file__
    dataset = os.path.abspath(filename).split('/')[-2]

    def wrapper(f):
        lines = inspect.getsource(f).split('\n')
        lines = lines[:-1]  # Seems to include a trailing newline

        # Hacky way to get just the function body
        i = 0
        while True:
            if "():" in lines[i]:
                break
            i = i + 1

        fn = lines[i:]
        fn += ['FN = ' + f.__name__]
        queries[dataset].append([name, '\n'.join(fn)])

        return f

    return wrapper
项目:logfury    作者:ppolewicz    | 项目源码 | 文件源码
def get_class_that_defined_method(meth):
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
            if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__  # fallback to __qualname__ parsing
    if inspect.isfunction(meth):
        if not hasattr(meth, '__qualname__'):
            pass  # python too old
        else:
            try:
                cls = getattr(
                    inspect.getmodule(meth),
                    meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0]
                )  # yapf: disable
            except AttributeError:  # defined in an exec() on new python?
                cls = 'exec'
            if isinstance(cls, type):
                return cls
    return None
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
        renderer=None):
    """Render text documentation, given an object or a path to an object."""
    if renderer is None:
        renderer = text
    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 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' + renderer.document(object, name)
项目:splunk_ta_ps4_f1_2016    作者:jonathanvarley    | 项目源码 | 文件源码
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map