Debian Codegraph @

pypy/module/cpyext/import_.py

raw symbols SCIP
1 from pypy.module.cpyext.api import (
2 cpython_api, PyObject, CONST_STRING, CANNOT_FAIL, cts)
3 from rpython.rtyper.lltypesystem import lltype, rffi
4 from pypy.interpreter.error import OperationError, oefmt
5 from pypy.interpreter.module import Module
6 from pypy.interpreter.pycode import PyCode
7 from pypy.module.imp import importing
8 from pypy.objspace.std.dictmultiobject import W_DictMultiObject
9
10 @cpython_api([PyObject], PyObject)
11 def PyImport_Import(space, w_name):
12 """
13 This is a higher-level interface that calls the current "import hook function".
14 It invokes the __import__() function from the __builtins__ of the
15 current globals. This means that the import is done using whatever import hooks
16 are installed in the current environment, e.g. by rexec or ihooks.
17
18 Always uses absolute imports."""
19 caller = space.getexecutioncontext().gettopframe_nohidden()
20 # Get the builtins from current globals
21 if caller is not None:
22 w_globals = caller.get_w_globals()
23 w_builtin = space.getitem(w_globals, space.newtext('__builtins__'))
24 else:
25 # No globals -- use standard builtins, and fake globals
26 w_builtin = space.getbuiltinmodule('builtins')
27 w_globals = space.newdict()
28 space.setitem(w_globals, space.newtext("__builtins__"), w_builtin)
29
30 # Get the __import__ function from the builtins
31 if space.isinstance_w(w_builtin, space.w_dict):
32 w_import = space.getitem(w_builtin, space.newtext("__import__"))
33 else:
34 w_import = space.getattr(w_builtin, space.newtext("__import__"))
35
36 # Call the __import__ function with the proper argument list
37 # Always use absolute import here.
38 return space.call_function(w_import,
39 w_name, w_globals, w_globals,
40 space.newlist([space.newtext("__doc__")]))
41
42 @cpython_api([CONST_STRING], PyObject)
43 def PyImport_ImportModule(space, name):
44 return PyImport_Import(space, space.newtext(rffi.charp2str(name)))
45
46 @cpython_api([CONST_STRING], PyObject)
47 def PyImport_ImportModuleNoBlock(space, name):
48 space.warn(
49 space.newtext('PyImport_ImportModuleNoBlock() is not non-blocking'),
50 space.w_RuntimeWarning)
51 return PyImport_Import(space, space.newtext(rffi.charp2str(name)))
52
53
54 @cts.decl(
55 '''PyObject* PyImport_ImportModuleLevelObject(
56 PyObject *name, PyObject *given_globals, PyObject *locals,
57 PyObject *given_fromlist, int level)''')
58 def PyImport_ImportModuleLevelObject(space, w_name, w_glob, w_loc, w_fromlist, level):
59 level = rffi.cast(lltype.Signed, level)
60 if w_glob is None:
61 w_glob = space.newdict()
62 else:
63 if level > 0 and not space.isinstance_w(w_glob, space.w_dict):
64 raise oefmt(space.w_TypeError, "globals must be a dict")
65 if w_fromlist is None:
66 w_fromlist = space.newlist([])
67 if w_name is None:
68 raise oefmt(space.w_ValueError, "Empty module name")
69 w_import = space.builtin.get('__import__')
70 if level < 0:
71 raise oefmt(space.w_ValueError, "level must be >= 0")
72 return space.call_function(
73 w_import, w_name, w_glob, w_loc, w_fromlist, space.newint(level))
74
75
76 @cpython_api([PyObject], PyObject)
77 def PyImport_ReloadModule(space, w_mod):
78 w_import = space.builtin.get('__import__')
79 w_imp = space.call_function(w_import, space.newtext('imp'))
80 return space.call_method(w_imp, 'reload', w_mod)
81
82 @cpython_api([CONST_STRING], PyObject, result_borrowed=True)
83 def PyImport_AddModule(space, name):
84 """Return the module object corresponding to a module name. The name
85 argument may be of the form package.module. First check the modules
86 dictionary if there's one there, and if not, create a new one and insert
87 it in the modules dictionary. Return NULL with an exception set on
88 failure.
89
90 This function does not load or import the module; if the module wasn't
91 already loaded, you will get an empty module object. Use
92 PyImport_ImportModule() or one of its variants to import a module.
93 Package structures implied by a dotted name for name are not created if
94 not already present."""
95 from pypy.module.imp.importing import check_sys_modules_w
96 modulename = rffi.charp2str(name)
97 w_mod = check_sys_modules_w(space, modulename)
98 if not w_mod or space.is_w(w_mod, space.w_None):
99 w_mod = Module(space, space.newtext(modulename))
100 space.setitem(space.sys.get('modules'), space.newtext(modulename), w_mod)
101 # return a borrowed ref --- assumes one copy in sys.modules
102 return w_mod
103
104 @cpython_api([], PyObject, result_borrowed=True)
105 def PyImport_GetModuleDict(space):
106 """Return the dictionary used for the module administration (a.k.a.
107 sys.modules). Note that this is a per-interpreter variable."""
108 w_modulesDict = space.sys.get('modules')
109 return w_modulesDict # borrowed ref
110
111 @cpython_api([PyObject], PyObject)
112 def PyImport_GetModule(space, w_name):
113 """Return the already imported module with the given name. If the module
114 has not been imported yet then returns NULL but does not set an error.
115 Returns NULL and sets an error if the lookup failed."""
116 w_modulesDict = space.sys.get('modules')
117 try:
118 return space.getitem(w_modulesDict, w_name)
119 except OperationError as e:
120 if e.match(space, space.w_KeyError):
121 return None
122 raise e
123
124 @cpython_api([rffi.CONST_CCHARP, PyObject], PyObject)
125 def PyImport_ExecCodeModule(space, name, w_code):
126 """Given a module name (possibly of the form package.module) and a code
127 object read from a Python bytecode file or obtained from the built-in
128 function compile(), load the module. Return a new reference to the module
129 object, or NULL with an exception set if an error occurred. Before Python
130 2.4, the module could still be created in error cases. Starting with Python
131 2.4, name is removed from sys.modules in error cases, and even if name was
132 already in sys.modules on entry to PyImport_ExecCodeModule(). Leaving
133 incompletely initialized modules in sys.modules is dangerous, as imports of
134 such modules have no way to know that the module object is an unknown (and
135 probably damaged with respect to the module author's intents) state.
136
137 The module's __file__ attribute will be set to the code object's
138 co_filename.
139
140 This function will reload the module if it was already imported. See
141 PyImport_ReloadModule() for the intended way to reload a module.
142
143 If name points to a dotted name of the form package.module, any package
144 structures not already created will still not be created.
145
146 name is removed from sys.modules in error cases."""
147 return PyImport_ExecCodeModuleEx(space, name, w_code,
148 lltype.nullptr(rffi.CONST_CCHARP.TO))
149
150
151 @cpython_api([rffi.CONST_CCHARP, PyObject, rffi.CONST_CCHARP], PyObject)
152 def PyImport_ExecCodeModuleEx(space, name, w_code, pathname):
153 """Like PyImport_ExecCodeModule(), but the __file__ attribute of
154 the module object is set to pathname if it is non-NULL."""
155 code = space.interp_w(PyCode, w_code)
156 w_name = space.newtext(rffi.constcharp2str(name))
157 if pathname:
158 pathname = rffi.constcharp2str(pathname)
159 else:
160 pathname = code.co_filename
161 w_mod = importing.add_module(space, w_name)
162 space.setattr(w_mod, space.newtext('__file__'), space.newfilename(pathname))
163 cpathname = importing.make_compiled_pathname(pathname)
164 importing.exec_code_module(space, w_mod, code, pathname, cpathname)
165 return w_mod
166
167 @cpython_api([], lltype.Void, error=CANNOT_FAIL)
168 def _PyImport_AcquireLock(space):
169 """Locking primitive to prevent parallel imports of the same module
170 in different threads to return with a partially loaded module.
171 These calls are serialized by the global interpreter lock."""
172 try:
173 space.call_method(space.getbuiltinmodule('imp'), 'acquire_lock')
174 except OperationError as e:
175 e.write_unraisable(space, "_PyImport_AcquireLock")
176
177 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
178 def _PyImport_ReleaseLock(space):
179 try:
180 space.call_method(space.getbuiltinmodule('imp'), 'release_lock')
181 return 1
182 except OperationError as e:
183 e.write_unraisable(space, "_PyImport_ReleaseLock")
184 return -1