python类getmodule()的实例源码

rhunittest.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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__ = ()
pydoc.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 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 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 22 收藏 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):
            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 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 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.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")
utils.py 文件源码 项目:abusehelper 作者: Exploit-install 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
dtcompat.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 19 收藏 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 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 31 收藏 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 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 29 收藏 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)
wsdl2dispatch.py 文件源码 项目:vspheretools 作者: devopshq 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
wsdl2dispatch.py 文件源码 项目:vspheretools 作者: devopshq 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
sflib.py 文件源码 项目:llk 作者: Tycx2ry 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
docscrape.py 文件源码 项目:cleverhans 作者: tensorflow 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
docscrape.py 文件源码 项目:cleverhans 作者: tensorflow 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
html_test_runner.py 文件源码 项目:simLAB 作者: kamwar 项目源码 文件源码 阅读 26 收藏 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
sflib.py 文件源码 项目:spiderfoot 作者: wi-fi-analyzer 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
sflib.py 文件源码 项目:spiderfoot 作者: wi-fi-analyzer 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
yacc.py 文件源码 项目:aws-cfn-plex 作者: lordmuffin 项目源码 文件源码 阅读 30 收藏 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
yacc.py 文件源码 项目:aws-cfn-plex 作者: lordmuffin 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
doctest.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 22 收藏 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")
apiproxy_stub_map.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
doctest.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 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 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 21 收藏 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")
apiproxy_stub_map.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:sahriswiki 作者: prologic 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
functions.py 文件源码 项目:pydecor 作者: mplanchard 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
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)
utils.py 文件源码 项目:django-schemas 作者: ryannjohnson 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
ipdoctest.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
pydoc.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 53 收藏 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)
doctest.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 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.__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")


问题


面经


文章

微信
公众号

扫码关注公众号