python类getmodule()的实例源码

util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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.')
util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
doctest.py 文件源码 项目:chihu 作者: yelongyu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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")
doctest.py 文件源码 项目:Price-Comparator 作者: Thejas-1 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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")
pydoc.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
doctest.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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")
pydoc.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
doctest.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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")
log.py 文件源码 项目:highway.py 作者: PhilipTrauner 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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()
dtcompat.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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")
xunit.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
pydoc.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
doctest.py 文件源码 项目:Flask-NvRay-Blog 作者: rui7157 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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")
doctest.py 文件源码 项目:NeuroMobile 作者: AndrewADykman 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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")
ability_module.py 文件源码 项目:packetweaver 作者: ANSSI-FR 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
queries.py 文件源码 项目:esper 作者: scanner-research 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:logfury 作者: ppolewicz 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
pydoc.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
yacc.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号