当前位置: 首页>>代码示例>>Python>>正文


Python new.module方法代码示例

本文整理汇总了Python中new.module方法的典型用法代码示例。如果您正苦于以下问题:Python new.module方法的具体用法?Python new.module怎么用?Python new.module使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在new的用法示例。


在下文中一共展示了new.module方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _normalize_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def _normalize_module(module, depth=2):
    """
    Return the module specified by `module`.  In particular:
      - If `module` is a module, then return module.
      - If `module` is a string, then import and return the
        module with that name.
      - If `module` is None, then return the calling module.
        The calling module is assumed to be the module of
        the stack frame at the given depth in the call stack.
    """
    if inspect.ismodule(module):
        return module
    elif isinstance(module, (str, unicode)):
        return __import__(module, globals(), locals(), ["*"])
    elif module is None:
        return sys.modules[sys._getframe(depth).f_globals['__name__']]
    else:
        raise TypeError("Expected a module, string, or None") 
开发者ID:linuxscout,项目名称:mishkal,代码行数:20,代码来源:doctest24.py

示例2: _from_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
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") 
开发者ID:linuxscout,项目名称:mishkal,代码行数:21,代码来源:doctest24.py

示例3: DocFileTest

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def DocFileTest(path, module_relative=True, package=None,
                globs=None, parser=DocTestParser(), **options):
    if globs is None:
        globs = {}

    if package and not module_relative:
        raise ValueError("Package may only be specified for module-"
                         "relative paths.")

    # Relativize the path.
    if module_relative:
        package = _normalize_module(package)
        path = _module_relative_path(package, path)

    # Find the file and read it.
    name = os.path.basename(path)
    doc = open(path).read()

    # Convert it to a test, and wrap it in a DocFileCase.
    test = parser.get_doctest(doc, globs, name, path, 0)
    return DocFileCase(test, **options) 
开发者ID:linuxscout,项目名称:mishkal,代码行数:23,代码来源:doctest24.py

示例4: _from_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
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") 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:22,代码来源:dtcompat.py

示例5: save_type

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def save_type(self, obj):
    if getattr(new, obj.__name__, None) is obj:
        # Types in 'new' module claim their module is '__builtin__' but are not actually there
        save_global_byname(self, obj, 'new', obj.__name__)
    elif obj.__module__ == '__main__':
        # Types in __main__ are saved by value

        # Make sure we have a reference to type.__new__        
        if id(type.__new__) not in self.memo:
            self.save_reduce(getattr, (type, '__new__'), obj=type.__new__)
            self.write(pickle.POP)

        # Copy dictproxy to real dict
        d = dict(obj.__dict__)
        # Clean up unpickleable descriptors added by Python
        d.pop('__dict__', None)
        d.pop('__weakref__', None)
        
        args = (type(obj), obj.__name__, obj.__bases__, d)
        self.save_reduce(type.__new__, args, obj=obj)
    else:
        # Fallback to default behavior: save by reference
        pickle.Pickler.save_global(self, obj) 
开发者ID:ActiveState,项目名称:code,代码行数:25,代码来源:recipe-572213.py

示例6: _normalize_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def _normalize_module(module, depth=2):
    """
    Return the module specified by `module`.  In particular:
      - If `module` is a module, then return module.
      - If `module` is a string, then import and return the
        module with that name.
      - If `module` is None, then return the calling module.
        The calling module is assumed to be the module of
        the stack frame at the given depth in the call stack.
    """
    if inspect.ismodule(module):
        return module
    elif isinstance(module, six.string_types):
        return __import__(module, globals(), locals(), ["*"])
    elif module is None:
        return sys.modules[sys._getframe(depth).f_globals['__name__']]
    else:
        raise TypeError("Expected a module, string, or None") 
开发者ID:blackye,项目名称:luscan-devel,代码行数:20,代码来源:_doctest.py

示例7: _from_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
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 six.get_function_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") 
开发者ID:blackye,项目名称:luscan-devel,代码行数:21,代码来源:_doctest.py

示例8: _caller

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def _caller(tblist, skip):
    string = ""
    arr = []
    for file, line, name, text in tblist:
        if file[-10:] == "TestCmd.py":
                break
        arr = [(file, line, name, text)] + arr
    atfrom = "at"
    for file, line, name, text in arr[skip:]:
        if name in ("?", "<module>"):
            name = ""
        else:
            name = " (" + name + ")"
        string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
        atfrom = "\tfrom"
    return string 
开发者ID:turbulenz,项目名称:gyp,代码行数:18,代码来源:TestCmd.py

示例9: load_template_file

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def load_template_file(filename,
                       module_name=None,
                       analyzer_options=options.default_options,
                       compiler_options=None,
                       xspt_mode=False):
    # Note: The compiler module is imported here to avoid a circular dependency.
    from spitfire.compiler import compiler
    spt_compiler = compiler.Compiler(analyzer_options=analyzer_options,
                                     xspt_mode=xspt_mode)
    if compiler_options:
        for k, v in compiler_options.iteritems():
            setattr(spt_compiler, k, v)
    class_name = filename2classname(filename)
    if not module_name:
        module_name = class_name

    src_code = spt_compiler.compile_file(filename)
    module = load_module_from_src(src_code, filename, module_name)
    return getattr(module, class_name) 
开发者ID:youtube,项目名称:spitfire,代码行数:21,代码来源:util.py

示例10: load_template

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def load_template(template_src,
                  template_name,
                  analyzer_options=options.default_options,
                  compiler_options=None):
    class_name = filename2classname(template_name)
    filename = '<%s>' % class_name
    module_name = class_name
    # Note: The compiler module is imported here to avoid a circular dependency
    from spitfire.compiler import compiler
    spt_compiler = compiler.Compiler(analyzer_options=analyzer_options)
    if compiler_options:
        for k, v in compiler_options.iteritems():
            setattr(spt_compiler, k, v)
    src_code = spt_compiler.compile_template(template_src, class_name)
    module = load_module_from_src(src_code, filename, module_name)
    return getattr(module, class_name)


# a helper method to import a template without having to save it to disk 
开发者ID:youtube,项目名称:spitfire,代码行数:21,代码来源:util.py

示例11: filenameToModuleName

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def filenameToModuleName(fn):
    """
    Convert a name in the filesystem to the name of the Python module it is.

    This is agressive about getting a module name back from a file; it will
    always return a string.  Agressive means 'sometimes wrong'; it won't look
    at the Python path or try to do any error checking: don't use this method
    unless you already know that the filename you're talking about is a Python
    module.
    """
    fullName = os.path.abspath(fn)
    base = os.path.basename(fn)
    if not base:
        # this happens when fn ends with a path separator, just skit it
        base = os.path.basename(fn[:-1])
    modName = os.path.splitext(base)[0]
    while 1:
        fullName = os.path.dirname(fullName)
        if os.path.exists(os.path.join(fullName, "__init__.py")):
            modName = "%s.%s" % (os.path.basename(fullName), modName)
        else:
            break
    return modName 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:25,代码来源:reflect.py

示例12: testRebuild

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def testRebuild(self):
        """
        Rebuilding an unchanged module.
        """
        # This test would actually pass if rebuild was a no-op, but it
        # ensures rebuild doesn't break stuff while being a less
        # complex test than testFileRebuild.

        x = crash_test_dummy.X('a')

        rebuild.rebuild(crash_test_dummy, doLog=False)
        # Instance rebuilding is triggered by attribute access.
        x.do()
        self.failUnlessIdentical(x.__class__, crash_test_dummy.X)

        self.failUnlessIdentical(f, crash_test_dummy.foo) 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:18,代码来源:test_rebuild.py

示例13: _from_module

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
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):
            # XXX: Jython transition 2.5
            # Java classes appear as Python classes to inspect, but they
            # have no __module__ http://jython.org/bugs/1758279
            # org.python.modules uses Java classes to masq
            if not hasattr(object, '__module__'):
                return False
            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") 
开发者ID:ofermend,项目名称:medicare-demo,代码行数:27,代码来源:doctest.py

示例14: _module_relative_path

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def _module_relative_path(module, path):
    if not inspect.ismodule(module):
        raise TypeError, 'Expected a module: %r' % module
    if path.startswith('/'):
        raise ValueError, 'Module-relative files may not have absolute paths'

    # Find the base directory for the path.
    if hasattr(module, '__file__'):
        # A normal module/package
        basedir = os.path.split(module.__file__)[0]
    elif module.__name__ == '__main__':
        # An interactive session.
        if len(sys.argv)>0 and sys.argv[0] != '':
            basedir = os.path.split(sys.argv[0])[0]
        else:
            basedir = os.curdir
    else:
        # A module w/o __file__ (this includes builtins)
        raise ValueError("Can't resolve paths relative to the module " +
                         module + " (it has no __file__)")

    # Combine the base directory and the path.
    return os.path.join(basedir, *(path.split('/')))

######################################################################
## 2. Example & DocTest
######################################################################
## - An "example" is a <source, want> pair, where "source" is a
##   fragment of source code, and "want" is the expected output for
##   "source."  The Example class also includes information about
##   where the example was extracted from.
##
## - A "doctest" is a collection of examples, typically extracted from
##   a string (such as an object's docstring).  The DocTest class also
##   includes information about where the string was extracted from. 
开发者ID:linuxscout,项目名称:mishkal,代码行数:37,代码来源:doctest24.py

示例15: _get_test

# 需要导入模块: import new [as 别名]
# 或者: from new import module [as 别名]
def _get_test(self, obj, name, module, globs, source_lines):
        """
        Return a DocTest for the given object, if it defines a docstring;
        otherwise, return None.
        """
        # Extract the object's docstring.  If it doesn't have one,
        # then return None (no test for this object).
        if isinstance(obj, basestring):
            docstring = obj
        else:
            try:
                if obj.__doc__ is None:
                    docstring = ''
                else:
                    docstring = obj.__doc__
                    if not isinstance(docstring, basestring):
                        docstring = str(docstring)
            except (TypeError, AttributeError):
                docstring = ''

        # Find the docstring's location in the file.
        lineno = self._find_lineno(obj, source_lines)

        # Don't bother if the docstring is empty.
        if self._exclude_empty and not docstring:
            return None

        # Return a DocTest for this object.
        if module is None:
            filename = None
        else:
            filename = getattr(module, '__file__', module.__name__)
            if filename[-4:] in (".pyc", ".pyo"):
                filename = filename[:-1]
        return self._parser.get_doctest(docstring, globs, name,
                                        filename, lineno) 
开发者ID:linuxscout,项目名称:mishkal,代码行数:38,代码来源:doctest24.py


注:本文中的new.module方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。