本文整理汇总了Python中types.ModuleType类的典型用法代码示例。如果您正苦于以下问题:Python ModuleType类的具体用法?Python ModuleType怎么用?Python ModuleType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModuleType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, env, libs=None):
self.destroyed = False
libs = libs or ['prelude']
for lib in libs:
if 'darwin' in sys.platform:
prelude = join(dirname(realpath(__file__)), lib + '.dylib')
elif 'linux' in sys.platform:
prelude = join(dirname(realpath(__file__)), lib+ '.so')
else:
raise NotImplementedError
# XXX: yeah, don't do this
ctypes._dlopen(prelude, ctypes.RTLD_GLOBAL)
cgen = env['cgen']
self.__namespace = cgen.globals
self.__llmodule = cgen.module
if not detect_avx_support():
tc = le.TargetMachine.new(features='-avx', cm=le.CM_JITDEFAULT)
else:
tc = le.TargetMachine.new(features='', cm=le.CM_JITDEFAULT)
eb = le.EngineBuilder.new(self.__llmodule)
self.__engine = eb.create(tc)
#self.__engine.run_function(cgen.globals['__module'], [])
mod = ModuleType('blir_wrapper')
wrap_llvm_module(cgen.module, self.__engine, mod)
mod.__doc__ = 'Compiled LLVM wrapper module'
self.__mod = mod
示例2: __strict__
def __strict__(self):
ModuleType.__setattr__(self, "__class__", NormalModule)
if "." in self.__name__:
parent_name, leaf_name = self.__name__.rsplit(".", 1)
parent = sys.modules[parent_name]
setattr(parent, leaf_name, self) # this will __strict__ the parent
reload(self)
示例3: from_config_status
def from_config_status(cls, path):
"""Create an instance from a config.status file."""
code_cache = cls._CODE_CACHE
mtime = os.path.getmtime(path)
# cache the compiled code as it can be reused
# we cache it the first time, or if the file changed
if not path in code_cache or code_cache[path][0] != mtime:
# Add config.status manually to sys.modules so it gets picked up by
# iter_modules_in_path() for automatic dependencies.
mod = ModuleType('config.status')
mod.__file__ = path
sys.modules['config.status'] = mod
with open(path, 'rt') as fh:
source = fh.read()
code_cache[path] = (
mtime,
compile(source, path, 'exec', dont_inherit=1)
)
g = {
'__builtins__': __builtins__,
'__file__': path,
}
l = {}
exec(code_cache[path][1], g, l)
config = BuildConfig()
for name in l['__all__']:
setattr(config, name, l[name])
return config
示例4: InitPathesAndBuiltins
def InitPathesAndBuiltins():
sys.path.insert(0, eg.mainDir.encode('mbcs'))
sys.path.insert(1, eg.sitePackagesDir.encode('mbcs'))
import cFunctions
sys.modules["eg.cFunctions"] = cFunctions
eg.cFunctions = cFunctions
# add 'wx' to the builtin name space of every module
import __builtin__
__builtin__.wx = wx
# we create a package 'PluginModule' and set its path to the plugin-dir
# so we can simply use __import__ to load a plugin file
corePluginPackage = ModuleType("eg.CorePluginModule")
corePluginPackage.__path__ = [eg.corePluginDir]
sys.modules["eg.CorePluginModule"] = corePluginPackage
eg.CorePluginModule = corePluginPackage
# we create a package 'PluginModule' and set its path to the plugin-dir
# so we can simply use __import__ to load a plugin file
if not os.path.exists(eg.localPluginDir):
os.makedirs(eg.localPluginDir)
userPluginPackage = ModuleType("eg.UserPluginModule")
userPluginPackage.__path__ = [eg.localPluginDir]
sys.modules["eg.UserPluginModule"] = userPluginPackage
eg.UserPluginModule = userPluginPackage
示例5: test_get_modpath_all_multi
def test_get_modpath_all_multi(self):
module = ModuleType('nothing')
module.__path__ = ['/path/to/here', '/path/to/there']
self.assertEqual(
indexer.modpath_all(module, None),
['/path/to/here', '/path/to/there'],
)
示例6: test_iter_builders_verify_export_target
def test_iter_builders_verify_export_target(self):
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
'invalid.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
class FakeArtifactRegistry(ArtifactRegistry):
def verify_export_target(self, export_target):
return 'invalid.js' not in export_target
registry = FakeArtifactRegistry(
'calmjs.artifacts', _working_set=mock_ws)
# the invalid.js should be filtered out
with pretty_logging(stream=mocks.StringIO()) as stream:
self.assertEqual(1, len(list(registry.iter_builders_for('app'))))
self.assertIn("invalid.js' has been rejected", stream.getvalue())
示例7: test_iter_builders_side_effect_build_issue
def test_iter_builders_side_effect_build_issue(self):
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
# clog the build directory so build cannot happen
with open(join(root), 'w'):
pass
ep, toolchain, spec = next(registry.iter_builders_for('app'))
check = []
spec.advise('after_prepare', check.append, True)
with pretty_logging(stream=mocks.StringIO()) as stream:
with self.assertRaises(ToolchainAbort):
toolchain(spec)
self.assertIn(
"an advice in group 'before_prepare' triggered an abort",
stream.getvalue())
# should have stopped at before_prepare
self.assertFalse(check)
示例8: test_iter_builders_side_effect
def test_iter_builders_side_effect(self):
# inject dummy module and add cleanup
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
self.assertFalse(exists(root))
ep, toolchain, spec = next(registry.iter_builders_for('app'))
self.assertFalse(exists(root))
# directory only created after the toolchain is executed
toolchain(spec)
self.assertTrue(exists(root))
示例9: test_task_dependencies_with_post_definition_injections_custom_names
def test_task_dependencies_with_post_definition_injections_custom_names(self):
import pybuilder.reactor
with patch("pybuilder.reactor.Task"):
@task
def task1():
pass
@task
@depends(task1)
def task2():
pass
@task("task_3")
@depends(task1)
@dependents(task2)
def task3():
pass
module1 = ModuleType("mock_module_one")
module1.task1 = task1
module1.task2 = task2
module2 = ModuleType("mock_module_two")
module2.task3 = task3
self.reactor.collect_tasks_and_actions_and_initializers(module1)
pybuilder.reactor.Task.assert_has_calls([call("task1", task1, [], ''),
call("task2", task2, [TaskDependency(task1)], '')])
self.reactor.collect_tasks_and_actions_and_initializers(module2)
pybuilder.reactor.Task.assert_has_calls([call("task_3", task3, [TaskDependency(task1)], '')])
self.execution_manager.register_late_task_dependencies.assert_has_calls(
[call({}), call({"task2": [TaskDependency("task_3")]})])
示例10: modify_document
def modify_document(self, doc):
if self.failed:
return
from types import ModuleType
module_name = 'bk_script_' + str(uuid.uuid4()).replace('-', '')
module = ModuleType(module_name)
module.__dict__['__file__'] = abspath(self._path)
# This is to prevent the module from being gc'd before the
# document is. A symptom of a gc'd module is that its
# globals become None.
if not hasattr(doc, '_ScriptHandler__modules'):
setattr(doc, '_ScriptHandler__modules', [])
doc.__modules.append(module)
old_doc = curdoc()
set_curdoc(doc)
old_io = self._monkeypatch_io()
try:
exec(self._code, module.__dict__)
newdoc = curdoc()
# script is supposed to edit the doc not replace it
if newdoc is not doc:
raise RuntimeError("Script at '%s' replaced the output document" % (self._path))
except Exception as e:
self._failed = True
import traceback
self._error_detail = traceback.format_exc()
exc_type, exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt)
finally:
self._unmonkeypatch_io(old_io)
set_curdoc(old_doc)
示例11: new_module
def new_module(name, doc=None):
import sys
from types import ModuleType
m = ModuleType(name, doc)
m.__file__ = name + '.py'
sys.modules[name] = m
return m
示例12: __init__
def __init__(self, module, locals):
ModuleType.__init__(self, locals['__name__'])
self._imports = {}
ns = self.__dict__
ns.update(locals)
ns['__module__'] = self
lazy_symbols = {}
for symbol in module._get_symbol_names():
lazy_symbols[symbol] = ns[symbol] = _marker
ns.update(__dict__=LazyDict(self),
__bases__=(ModuleType,),
add_submodule=self.add_submodule)
def __getattribute__(_, name):
v = ns.get(name, _marker)
if v is not _marker:
return v
if name in lazy_symbols:
s = module._get_symbol(ns, name)
return s
elif name in self._imports:
m = __import__(self._imports[name], {}, {}, ' ')
ns[name] = m
return m
raise AttributeError(name)
LazyNamespace.__getattribute__ = __getattribute__
示例13: __new__
def __new__(meta, name, bases, dict):
mod = ModuleType(name, dict.get("__doc__"))
for key, obj in dict.items():
if isinstance(obj, FunctionType):
obj = meta.chained_function(meta, obj, mod)
mod.__dict__[key] = obj
return mod
示例14: test_configure
def test_configure():
# a) keyword arguments
assert not hasattr(_Options, 'foo')
configure(foo='bar')
assert hasattr(_Options, 'foo')
del _Options.foo
# b) module
assert not hasattr(_Options, 'foo')
module = ModuleType('config')
module.MONGODB_FOO = 'bar'
module.NON_MONGO_ATTR = 'bar'
configure(foo='bar')
assert not hasattr(_Options, 'NON_MONGO_ATTR')
assert not hasattr(_Options, 'MONGODB_FOO')
assert hasattr(_Options, 'foo')
del _Options.foo
# c) non-module (fails silently)
try:
configure(42)
configure(None)
configure('foobar')
except Exception:
pytest.fail('configure() should fail silently on invalid input.')
示例15: test_update_artifact_metadata
def test_update_artifact_metadata(self):
# inject dummy module and add cleanup
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('requires.txt', '\n'.join([
'calmjs',
])),
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
# mock a version of calmjs within that environment too
utils.make_dummy_dist(self, (
('entry_points.txt', ''),
), 'calmjs', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
self.assertTrue(exists(registry.metadata.get('app')))
with pretty_logging(stream=mocks.StringIO()) as s:
registry.update_artifact_metadata('calmjs', {})
self.assertIn(
"package 'calmjs' has not declare any artifacts", s.getvalue())