本文整理汇总了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")
示例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")
示例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)
示例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")
示例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)
示例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")
示例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")
示例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
示例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)
示例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
示例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
示例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)
示例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")
示例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.
示例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)