blob: 5b63bc5526f39908f7bd1c8431e7ba5ea6e429cf [file] [log] [blame]
Brett Cannonafccd632009-01-20 02:21:27 +00001:mod:`importlib` -- An implementation of :keyword:`import`
2==========================================================
3
4.. module:: importlib
5 :synopsis: An implementation of the import machinery.
6
7.. moduleauthor:: Brett Cannon <brett@python.org>
8.. sectionauthor:: Brett Cannon <brett@python.org>
9
10.. versionadded:: 3.1
11
12
13Introduction
14------------
15
16The purpose of the :mod:`importlib` package is two-fold. One is to provide an
17implementation of the :keyword:`import` statement (and thus, by extension, the
18:func:`__import__` function) in Python source code. This provides an
Tarek Ziadé434caaa2009-05-14 12:48:09 +000019implementation of :keyword:`import` which is portable to any Python
Brett Cannonafccd632009-01-20 02:21:27 +000020interpreter. This also provides a reference implementation which is easier to
Brett Cannondebb98d2009-02-16 04:18:01 +000021comprehend than one in a programming language other than Python.
Brett Cannonafccd632009-01-20 02:21:27 +000022
23Two, the components to implement :keyword:`import` can be exposed in this
24package, making it easier for users to create their own custom objects (known
Brett Cannondebb98d2009-02-16 04:18:01 +000025generically as an :term:`importer`) to participate in the import process.
26Details on providing custom importers can be found in :pep:`302`.
Brett Cannonafccd632009-01-20 02:21:27 +000027
28.. seealso::
29
30 :ref:`import`
31 The language reference for the :keyword:`import` statement.
32
33 `Packages specification <http://www.python.org/doc/essays/packages.html>`__
34 Original specification of packages. Some semantics have changed since
35 the writing of this document (e.g. redirecting based on :keyword:`None`
36 in :data:`sys.modules`).
37
38 The :func:`.__import__` function
39 The built-in function for which the :keyword:`import` statement is
Guido van Rossum09613542009-03-30 20:34:57 +000040 syntactic sugar.
Brett Cannonafccd632009-01-20 02:21:27 +000041
42 :pep:`235`
43 Import on Case-Insensitive Platforms
44
45 :pep:`263`
46 Defining Python Source Code Encodings
47
48 :pep:`302`
49 New Import Hooks.
50
51 :pep:`328`
52 Imports: Multi-Line and Absolute/Relative
53
54 :pep:`366`
55 Main module explicit relative imports
56
57 :pep:`3128`
58 Using UTF-8 as the Default Source Encoding
59
60
61Functions
62---------
63
Brett Cannon78246b62009-01-25 04:56:30 +000064.. function:: __import__(name, globals={}, locals={}, fromlist=list(), level=0)
Brett Cannonafccd632009-01-20 02:21:27 +000065
66 An implementation of the built-in :func:`__import__` function. See the
67 built-in function's documentation for usage instructions.
68
69.. function:: import_module(name, package=None)
70
Brett Cannon33418c82009-01-22 18:37:20 +000071 Import a module. The *name* argument specifies what module to
Brett Cannonafccd632009-01-20 02:21:27 +000072 import in absolute or relative terms
73 (e.g. either ``pkg.mod`` or ``..mod``). If the name is
Guido van Rossum09613542009-03-30 20:34:57 +000074 specified in relative terms, then the *package* argument must be set to
75 the name of the package which is to act as the anchor for resolving the
Brett Cannonafccd632009-01-20 02:21:27 +000076 package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
Brett Cannon2c318a12009-02-07 01:15:27 +000077 ``pkg.mod``).
Brett Cannon78246b62009-01-25 04:56:30 +000078
Brett Cannon2c318a12009-02-07 01:15:27 +000079 The :func:`import_module` function acts as a simplifying wrapper around
Brett Cannon9f4cb1c2009-04-01 23:26:47 +000080 :func:`importlib.__import__`. This means all semantics of the function are
81 derived from :func:`importlib.__import__`, including requiring the package
82 from which an import is occurring to have been previously imported
83 (i.e., *package* must already be imported). The most important difference
84 is that :func:`import_module` returns the most nested package or module
85 that was imported (e.g. ``pkg.mod``), while :func:`__import__` returns the
Guido van Rossum09613542009-03-30 20:34:57 +000086 top-level package or module (e.g. ``pkg``).
87
Brett Cannon78246b62009-01-25 04:56:30 +000088
Brett Cannon2a922ed2009-03-09 03:35:50 +000089:mod:`importlib.abc` -- Abstract base classes related to import
90---------------------------------------------------------------
91
92.. module:: importlib.abc
93 :synopsis: Abstract base classes related to import
94
95The :mod:`importlib.abc` module contains all of the core abstract base classes
96used by :keyword:`import`. Some subclasses of the core abstract base classes
97are also provided to help in implementing the core ABCs.
98
99
100.. class:: Finder
101
102 An abstract base class representing a :term:`finder`.
Guido van Rossum09613542009-03-30 20:34:57 +0000103 See :pep:`302` for the exact definition for a finder.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000104
Brett Cannon9c751b72009-03-09 16:28:16 +0000105 .. method:: find_module(fullname, path=None)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000106
107 An abstract method for finding a :term:`loader` for the specified
108 module. If the :term:`finder` is found on :data:`sys.meta_path` and the
Guido van Rossum09613542009-03-30 20:34:57 +0000109 module to be searched for is a subpackage or module then *path* will
110 be the value of :attr:`__path__` from the parent package. If a loader
Brett Cannon2a922ed2009-03-09 03:35:50 +0000111 cannot be found, :keyword:`None` is returned.
112
Brett Cannon2a922ed2009-03-09 03:35:50 +0000113
114.. class:: Loader
115
116 An abstract base class for a :term:`loader`.
Guido van Rossum09613542009-03-30 20:34:57 +0000117 See :pep:`302` for the exact definition for a loader.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000118
Brett Cannon9c751b72009-03-09 16:28:16 +0000119 .. method:: load_module(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000120
121 An abstract method for loading a module. If the module cannot be
122 loaded, :exc:`ImportError` is raised, otherwise the loaded module is
123 returned.
124
Guido van Rossum09613542009-03-30 20:34:57 +0000125 If the requested module already exists in :data:`sys.modules`, that
Brett Cannon2a922ed2009-03-09 03:35:50 +0000126 module should be used and reloaded.
Guido van Rossum09613542009-03-30 20:34:57 +0000127 Otherwise the loader should create a new module and insert it into
128 :data:`sys.modules` before any loading begins, to prevent recursion
129 from the import. If the loader inserted a module and the load fails, it
Brett Cannon2a922ed2009-03-09 03:35:50 +0000130 must be removed by the loader from :data:`sys.modules`; modules already
131 in :data:`sys.modules` before the loader began execution should be left
132 alone. The :func:`importlib.util.module_for_loader` decorator handles
133 all of these details.
134
Guido van Rossum09613542009-03-30 20:34:57 +0000135 The loader should set several attributes on the module.
136 (Note that some of these attributes can change when a module is
137 reloaded.)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000138
139 - :attr:`__name__`
140 The name of the module.
141
142 - :attr:`__file__`
143 The path to where the module data is stored (not set for built-in
144 modules).
145
146 - :attr:`__path__`
Guido van Rossum09613542009-03-30 20:34:57 +0000147 A list of strings specifying the search path within a
Brett Cannon2a922ed2009-03-09 03:35:50 +0000148 package. This attribute is not set on modules.
149
150 - :attr:`__package__`
151 The parent package for the module/package. If the module is
152 top-level then it has a value of the empty string. The
153 :func:`importlib.util.set_package` decorator can handle the details
154 for :attr:`__package__`.
155
156 - :attr:`__loader__`
Guido van Rossum09613542009-03-30 20:34:57 +0000157 The loader used to load the module.
158 (This is not set by the built-in import machinery,
159 but it should be set whenever a :term:`loader` is used.)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000160
161
162.. class:: ResourceLoader
163
164 An abstract base class for a :term:`loader` which implements the optional
165 :pep:`302` protocol for loading arbitrary resources from the storage
166 back-end.
167
Brett Cannon9c751b72009-03-09 16:28:16 +0000168 .. method:: get_data(path)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000169
170 An abstract method to return the bytes for the data located at *path*.
Guido van Rossum09613542009-03-30 20:34:57 +0000171 Loaders that have a file-like storage back-end
Brett Cannon16248a42009-04-01 20:47:14 +0000172 that allows storing arbitrary data
Guido van Rossum09613542009-03-30 20:34:57 +0000173 can implement this abstract method to give direct access
Brett Cannon2a922ed2009-03-09 03:35:50 +0000174 to the data stored. :exc:`IOError` is to be raised if the *path* cannot
175 be found. The *path* is expected to be constructed using a module's
Brett Cannon16248a42009-04-01 20:47:14 +0000176 :attr:`__file__` attribute or an item from a package's :attr:`__path__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000177
178
179.. class:: InspectLoader
180
181 An abstract base class for a :term:`loader` which implements the optional
Guido van Rossum09613542009-03-30 20:34:57 +0000182 :pep:`302` protocol for loaders that inspect modules.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000183
Brett Cannona113ac52009-03-15 01:41:33 +0000184 .. method:: get_code(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000185
Brett Cannona113ac52009-03-15 01:41:33 +0000186 An abstract method to return the :class:`code` object for a module.
187 :keyword:`None` is returned if the module does not have a code object
188 (e.g. built-in module). :exc:`ImportError` is raised if loader cannot
189 find the requested module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000190
Brett Cannon9c751b72009-03-09 16:28:16 +0000191 .. method:: get_source(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000192
193 An abstract method to return the source of a module. It is returned as
Guido van Rossum09613542009-03-30 20:34:57 +0000194 a text string with universal newlines. Returns :keyword:`None` if no
Brett Cannon2a922ed2009-03-09 03:35:50 +0000195 source is available (e.g. a built-in module). Raises :exc:`ImportError`
196 if the loader cannot find the module specified.
197
Brett Cannona113ac52009-03-15 01:41:33 +0000198 .. method:: is_package(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000199
Brett Cannona113ac52009-03-15 01:41:33 +0000200 An abstract method to return a true value if the module is a package, a
201 false value otherwise. :exc:`ImportError` is raised if the
202 :term:`loader` cannot find the module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000203
204
Brett Cannon69194272009-07-20 04:23:48 +0000205.. class:: ExecutionLoader
206
207 An abstract base class which inherits from :class:`InspectLoader` that,
Brett Cannon23460292009-07-20 22:59:00 +0000208 when implemented, helps a module to be executed as a script. The ABC
Brett Cannon69194272009-07-20 04:23:48 +0000209 represents an optional :pep:`302` protocol.
210
211 .. method:: get_filename(fullname)
212
213 An abstract method that is to return the value for :attr:`__file__` for
214 the specified module. If no path is available, :exc:`ImportError` is
215 raised.
216
217
Brett Cannon2a922ed2009-03-09 03:35:50 +0000218.. class:: PyLoader
219
Brett Cannon69194272009-07-20 04:23:48 +0000220 An abstract base class inheriting from
221 :class:`importlib.abc.ExecutionLoader` and
222 :class:`importlib.abc.ResourceLoader` designed to ease the loading of
Brett Cannon2a922ed2009-03-09 03:35:50 +0000223 Python source modules (bytecode is not handled; see
224 :class:`importlib.abc.PyPycLoader` for a source/bytecode ABC). A subclass
225 implementing this ABC will only need to worry about exposing how the source
226 code is stored; all other details for loading Python source code will be
227 handled by the concrete implementations of key methods.
228
Brett Cannon9c751b72009-03-09 16:28:16 +0000229 .. method:: source_path(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000230
231 An abstract method that returns the path to the source code for a
Brett Cannon62538712009-08-18 23:54:07 +0000232 module. Should return :keyword:`None` if there is no source code or
233 raise :exc:`ImportError` if the module cannot be found.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000234
Brett Cannon69194272009-07-20 04:23:48 +0000235 .. method:: get_filename(fullname)
236
237 A concrete implementation of
238 :meth:`importlib.abc.ExecutionLoader.get_filename` that
239 relies on :meth:`source_path`. If :meth:`source_path` returns
240 :keyword:`None`, then :exc:`ImportError` is raised.
241
Brett Cannon9c751b72009-03-09 16:28:16 +0000242 .. method:: load_module(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000243
244 A concrete implementation of :meth:`importlib.abc.Loader.load_module`
Brett Cannonad876c72009-03-09 07:53:09 +0000245 that loads Python source code. All needed information comes from the
246 abstract methods required by this ABC. The only pertinent assumption
247 made by this method is that when loading a package
248 :attr:`__path__` is set to ``[os.path.dirname(__file__)]``.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000249
Brett Cannon9c751b72009-03-09 16:28:16 +0000250 .. method:: get_code(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000251
252 A concrete implementation of
253 :meth:`importlib.abc.InspectLoader.get_code` that creates code objects
Guido van Rossum09613542009-03-30 20:34:57 +0000254 from Python source code, by requesting the source code (using
255 :meth:`source_path` and :meth:`get_data`), converting it to standard
256 newlines, and compiling it with the built-in :func:`compile` function.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000257
Brett Cannond43b30b2009-03-10 03:29:23 +0000258 .. method:: get_source(fullname)
259
260 A concrete implementation of
261 :meth:`importlib.abc.InspectLoader.get_source`. Uses
Brett Cannon69194272009-07-20 04:23:48 +0000262 :meth:`importlib.abc.ResourceLoader.get_data` and :meth:`source_path`
263 to get the source code. It tries to guess the source encoding using
Guido van Rossum09613542009-03-30 20:34:57 +0000264 :func:`tokenize.detect_encoding`.
Brett Cannond43b30b2009-03-10 03:29:23 +0000265
Brett Cannon2a922ed2009-03-09 03:35:50 +0000266
267.. class:: PyPycLoader
268
269 An abstract base class inheriting from :class:`importlib.abc.PyLoader`.
270 This ABC is meant to help in creating loaders that support both Python
271 source and bytecode.
272
Brett Cannon9c751b72009-03-09 16:28:16 +0000273 .. method:: source_mtime(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000274
275 An abstract method which returns the modification time for the source
276 code of the specified module. The modification time should be an
Brett Cannon69194272009-07-20 04:23:48 +0000277 integer. If there is no source code, return :keyword:`None`. If the
Brett Cannon2a922ed2009-03-09 03:35:50 +0000278 module cannot be found then :exc:`ImportError` is raised.
279
Brett Cannon9c751b72009-03-09 16:28:16 +0000280 .. method:: bytecode_path(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000281
282 An abstract method which returns the path to the bytecode for the
Guido van Rossum09613542009-03-30 20:34:57 +0000283 specified module, if it exists. It returns :keyword:`None`
284 if no bytecode exists (yet).
285 Raises :exc:`ImportError` if the module is not found.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000286
Brett Cannon69194272009-07-20 04:23:48 +0000287 .. method:: get_filename(fullname)
288
289 A concrete implementation of
290 :meth:`importlib.abc.ExecutionLoader.get_filename` that relies on
291 :meth:`importlib.abc.PyLoader.source_path` and :meth:`bytecode_path`.
292 If :meth:`source_path` returns a path, then that value is returned.
293 Else if :meth:`bytecode_path` returns a path, that path will be
294 returned. If a path is not available from both methods,
295 :exc:`ImportError` is raised.
296
Brett Cannon9c751b72009-03-09 16:28:16 +0000297 .. method:: write_bytecode(fullname, bytecode)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000298
299 An abstract method which has the loader write *bytecode* for future
300 use. If the bytecode is written, return :keyword:`True`. Return
301 :keyword:`False` if the bytecode could not be written. This method
302 should not be called if :data:`sys.dont_write_bytecode` is true.
Guido van Rossum09613542009-03-30 20:34:57 +0000303 The *bytecode* argument should be a bytes string or bytes array.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000304
305
Brett Cannon78246b62009-01-25 04:56:30 +0000306:mod:`importlib.machinery` -- Importers and path hooks
307------------------------------------------------------
308
309.. module:: importlib.machinery
310 :synopsis: Importers and path hooks
311
312This module contains the various objects that help :keyword:`import`
313find and load modules.
314
315.. class:: BuiltinImporter
316
Brett Cannon2a922ed2009-03-09 03:35:50 +0000317 An :term:`importer` for built-in modules. All known built-in modules are
318 listed in :data:`sys.builtin_module_names`. This class implements the
Brett Cannona113ac52009-03-15 01:41:33 +0000319 :class:`importlib.abc.Finder` and :class:`importlib.abc.InspectLoader`
320 ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000321
322 Only class methods are defined by this class to alleviate the need for
323 instantiation.
324
Brett Cannon78246b62009-01-25 04:56:30 +0000325
326.. class:: FrozenImporter
327
Brett Cannon2a922ed2009-03-09 03:35:50 +0000328 An :term:`importer` for frozen modules. This class implements the
Brett Cannon8d110132009-03-15 02:20:16 +0000329 :class:`importlib.abc.Finder` and :class:`importlib.abc.InspectLoader`
330 ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000331
332 Only class methods are defined by this class to alleviate the need for
333 instantiation.
334
Brett Cannondebb98d2009-02-16 04:18:01 +0000335
336.. class:: PathFinder
337
Brett Cannon2a922ed2009-03-09 03:35:50 +0000338 :term:`Finder` for :data:`sys.path`. This class implements the
339 :class:`importlib.abc.Finder` ABC.
Brett Cannondebb98d2009-02-16 04:18:01 +0000340
341 This class does not perfectly mirror the semantics of :keyword:`import` in
342 terms of :data:`sys.path`. No implicit path hooks are assumed for
343 simplification of the class and its semantics.
344
Brett Cannon1b184d52009-11-07 08:22:58 +0000345 Only class methods are defined by this class to alleviate the need for
Brett Cannondebb98d2009-02-16 04:18:01 +0000346 instantiation.
347
348 .. classmethod:: find_module(fullname, path=None)
349
350 Class method that attempts to find a :term:`loader` for the module
Brett Cannon2a922ed2009-03-09 03:35:50 +0000351 specified by *fullname* on :data:`sys.path` or, if defined, on
Brett Cannondebb98d2009-02-16 04:18:01 +0000352 *path*. For each path entry that is searched,
353 :data:`sys.path_importer_cache` is checked. If an non-false object is
Brett Cannon2a922ed2009-03-09 03:35:50 +0000354 found then it is used as the :term:`finder` to look for the module
355 being searched for. If no entry is found in
Brett Cannondebb98d2009-02-16 04:18:01 +0000356 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
357 searched for a finder for the path entry and, if found, is stored in
358 :data:`sys.path_importer_cache` along with being queried about the
Brett Cannon2a922ed2009-03-09 03:35:50 +0000359 module. If no finder is ever found then :keyword:`None` is returned.
Brett Cannond2e7b332009-02-17 02:45:03 +0000360
361
362:mod:`importlib.util` -- Utility code for importers
363---------------------------------------------------
364
365.. module:: importlib.util
366 :synopsis: Importers and path hooks
367
368This module contains the various objects that help in the construction of
369an :term:`importer`.
370
371.. function:: module_for_loader(method)
372
Guido van Rossum09613542009-03-30 20:34:57 +0000373 A :term:`decorator` for a :term:`loader` method,
374 to handle selecting the proper
Brett Cannond2e7b332009-02-17 02:45:03 +0000375 module object to load with. The decorated method is expected to have a call
Brett Cannon2a922ed2009-03-09 03:35:50 +0000376 signature taking two positional arguments
377 (e.g. ``load_module(self, module)``) for which the second argument
Guido van Rossum09613542009-03-30 20:34:57 +0000378 will be the module **object** to be used by the loader.
379 Note that the decorator
Brett Cannon57b46f52009-03-02 14:38:26 +0000380 will not work on static methods because of the assumption of two
Brett Cannon2a922ed2009-03-09 03:35:50 +0000381 arguments.
Brett Cannond2e7b332009-02-17 02:45:03 +0000382
Guido van Rossum09613542009-03-30 20:34:57 +0000383 The decorated method will take in the **name** of the module to be loaded
384 as expected for a :term:`loader`. If the module is not found in
Brett Cannon57b46f52009-03-02 14:38:26 +0000385 :data:`sys.modules` then a new one is constructed with its
386 :attr:`__name__` attribute set. Otherwise the module found in
387 :data:`sys.modules` will be passed into the method. If an
Brett Cannond2e7b332009-02-17 02:45:03 +0000388 exception is raised by the decorated method and a module was added to
389 :data:`sys.modules` it will be removed to prevent a partially initialized
Brett Cannon57b46f52009-03-02 14:38:26 +0000390 module from being in left in :data:`sys.modules`. If the module was already
391 in :data:`sys.modules` then it is left alone.
Brett Cannond2e7b332009-02-17 02:45:03 +0000392
Guido van Rossum09613542009-03-30 20:34:57 +0000393 Use of this decorator handles all the details of which module object a
Brett Cannon57b46f52009-03-02 14:38:26 +0000394 loader should initialize as specified by :pep:`302`.
395
Brett Cannon2cf03a82009-03-10 05:17:37 +0000396.. function:: set_loader(fxn)
397
Guido van Rossum09613542009-03-30 20:34:57 +0000398 A :term:`decorator` for a :term:`loader` method,
399 to set the :attr:`__loader__`
Brett Cannon2cf03a82009-03-10 05:17:37 +0000400 attribute on loaded modules. If the attribute is already set the decorator
401 does nothing. It is assumed that the first positional argument to the
402 wrapped method is what :attr:`__loader__` should be set to.
403
Brett Cannon2cf03a82009-03-10 05:17:37 +0000404.. function:: set_package(fxn)
Brett Cannon57b46f52009-03-02 14:38:26 +0000405
406 A :term:`decorator` for a :term:`loader` to set the :attr:`__package__`
407 attribute on the module returned by the loader. If :attr:`__package__` is
408 set and has a value other than :keyword:`None` it will not be changed.
409 Note that the module returned by the loader is what has the attribute
410 set on and not the module found in :data:`sys.modules`.
Guido van Rossum09613542009-03-30 20:34:57 +0000411
Brett Cannon16248a42009-04-01 20:47:14 +0000412 Reliance on this decorator is discouraged when it is possible to set
413 :attr:`__package__` before the execution of the code is possible. By
414 setting it before the code for the module is executed it allows the
415 attribute to be used at the global level of the module during
416 initialization.
417
Brett Cannon9f4cb1c2009-04-01 23:26:47 +0000418
419Example
420-------
421
Brett Cannonbc6c2b52009-04-01 23:36:48 +0000422Below is an example meta path importer that uses a dict for back-end storage
423for source code. While not an optimal solution -- manipulations of
424:attr:`__path__` on packages does not influence import -- it does illustrate
425what little is required to implement an importer.
426
Brett Cannon9f4cb1c2009-04-01 23:26:47 +0000427.. testcode::
428
429 """An importer where source is stored in a dict."""
430 from importlib import abc
431
432
433 class DictImporter(abc.Finder, abc.PyLoader):
434
435 """A meta path importer that stores source code in a dict.
436
437 The keys are the module names -- packages must end in ``.__init__``.
438 The values must be something that can be passed to 'bytes'.
439
440 """
441
442 def __init__(self, memory):
443 """Store the dict."""
444 self.memory = memory
445
446 def contains(self, name):
447 """See if a module or package is in the dict."""
448 if name in self.memory:
449 return name
450 package_name = '{}.__init__'.format(name)
451 if package_name in self.memory:
452 return package_name
453 return False
454
455 __contains__ = contains # Convenience.
456
457 def find_module(self, fullname, path=None):
458 """Find the module in the dict."""
459 if fullname in self:
460 return self
461 return None
462
463 def source_path(self, fullname):
464 """Return the module name if the module is in the dict."""
465 if not fullname in self:
466 raise ImportError
467 return fullname
468
469 def get_data(self, path):
470 """Return the bytes for the source.
471
472 The value found in the dict is passed through 'bytes' before being
473 returned.
474
475 """
476 name = self.contains(path)
477 if not name:
478 raise IOError
479 return bytes(self.memory[name])
480
481 def is_package(self, fullname):
482 """Tell if module is a package based on whether the dict contains the
483 name with ``.__init__`` appended to it."""
484 if fullname not in self:
485 raise ImportError
486 if fullname in self.memory:
487 return False
488 # If name is in this importer but not as it is then it must end in
489 # ``__init__``.
490 else:
491 return True
492
493.. testcode::
494 :hide:
495
496 import importlib
497 import sys
498
499
500 # Build the dict; keys of name, value of __package__.
501 names = {'_top_level': '', '_pkg.__init__': '_pkg', '_pkg.mod': '_pkg'}
502 source = {name: "name = {!r}".format(name).encode() for name in names}
503
504 # Register the meta path importer.
505 importer = DictImporter(source)
506 sys.meta_path.append(importer)
507
508 # Sanity check.
509 for name in names:
510 module = importlib.import_module(name)
511 assert module.__name__ == name
512 assert getattr(module, 'name') == name
513 assert module.__loader__ is importer
514 assert module.__package__ == names[name]