To support this, Python has a way to put definitions in a file and use them in ascript or in an interactive instance of the interpreter. Such a file is called amodule; definitions from a module can be imported into other modules or intothe main module (the collection of variables that you have access to in ascript executed at the top level and in calculator mode).
This does not add the names of the functions defined in fibo directly tothe current namespace (see Python Scopes and Namespaces for more details);it only adds the module name fibo there. Usingthe module name you can access the functions:
A module can contain executable statements as well as function definitions.These statements are intended to initialize the module. They are executed onlythe first time the module name is encountered in an import statement. 1(They are also run if the file is executed as a script.)
Note that in general the practice of importing * from a module or package isfrowned upon, since it often causes poorly readable code. However, it is okay touse it to save typing in interactive sessions.
On file systems which support symlinks, the directory containing the inputscript is calculated after the symlink is followed. In other words thedirectory containing the symlink is not added to the module search path.
After initialization, Python programs can modify sys.path. Thedirectory containing the script being run is placed at the beginning of thesearch path, ahead of the standard library path. This means that scripts in thatdirectory will be loaded instead of modules of the same name in the librarydirectory. This is an error unless the replacement is intended. See sectionStandard Modules for more information.
To speed up loading modules, Python caches the compiled version of each modulein the __pycache__ directory under the name module.version.pyc,where the version encodes the format of the compiled file; it generally containsthe Python version number. For example, in CPython release 3.3 the compiledversion of spam.py would be cached as __pycache__/spam.cpython-33.pyc. Thisnaming convention allows compiled modules from different releases and differentversions of Python to coexist.
The __init__.py files are required to make Python treat directoriescontaining the file as packages. This prevents directories with a common name,such as string, from unintentionally hiding valid modules that occur lateron the module search path. In the simplest case, __init__.py can just bean empty file, but it can also execute initialization code for the package orset the __all__ variable, described later.
Note that when using from package import item, the item can be either asubmodule (or subpackage) of the package, or some other name defined in thepackage, like a function, class or variable. The import statement firsttests whether the item is defined in the package; if not, it assumes it is amodule and attempts to load it. If it fails to find it, an ImportErrorexception is raised.
Be aware that submodules might become shadowed by locally defined names. Forexample, if you added a reverse function to thesound/effects/__init__.py file, the from sound.effects import *would only import the two submodules echo and surround, but not thereverse submodule, because it is shadowed by the locally definedreverse function:
If __all__ is not defined, the statement from sound.effects import *does not import all submodules from the package sound.effects into thecurrent namespace; it only ensures that the package sound.effects hasbeen imported (possibly running any initialization code in __init__.py)and then imports whatever names are defined in the package. This includes anynames defined (and submodules explicitly loaded) by __init__.py. Italso includes any submodules of the package that were explicitly loaded byprevious import statements. Consider this code:
In this example, the echo and surround modules are imported in thecurrent namespace because they are defined in the sound.effects packagewhen the from...import statement is executed. (This also works when__all__ is defined.)
Remember, there is nothing wrong with using from package importspecific_submodule! In fact, this is the recommended notation unless theimporting module needs to use submodules with the same name from differentpackages.
When packages are structured into subpackages (as with the sound packagein the example), you can use absolute imports to refer to submodules of siblingspackages. For example, if the module sound.filters.vocoder needs to usethe echo module in the sound.effects package, it can use fromsound.effects import echo.
You can also write relative imports, with the from module import name formof import statement. These imports use leading dots to indicate the current andparent packages involved in the relative import. From the surroundmodule for example, you might use:
Note that relative imports are based on the name of the current module. Sincethe name of the main module is always "__main__", modules intended for useas the main module of a Python application must always use absolute imports.
It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScript libraries and frameworks that enable module usage (for example, other CommonJS and AMD-based module systems like RequireJS, and more recently Webpack and Babel).
To demonstrate usage of modules, we've created a simple set of examples that you can find on GitHub. These examples demonstrate a simple set of modules that create a element on a webpage, and then draw (and report information about) different shapes on the canvas.
Throughout this article, we've used .js extensions for our module files, but in other resources you may see the .mjs extension used instead. V8's documentation recommends this, for example. The reasons given are:
However, we decided to keep using .js, at least for the moment. To get modules to work correctly in a browser, you need to make sure that your server is serving them with a Content-Type header that contains a JavaScript MIME type such as text/javascript. If you don't, you'll get a strict MIME type checking error along the lines of "The server responded with a non-JavaScript MIME type" and the browser won't run your JavaScript. Most servers already set the correct type for .js files, but not yet for .mjs files. Servers that already serve .mjs files correctly include GitHub Pages and http-server for Node.js.
If you really value the clarity of using .mjs for modules versus using .js for "normal" JavaScript files, but don't want to run into the problem described above, you could always use .mjs during development and convert them to .js during your build step.
A more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file, followed by a comma-separated list of the features you want to export wrapped in curly braces. For example:
Note: In some module systems, you can use a module specifier like modules/square that isn't a relative or absolute path, and that doesn't have a file extension. This kind of specifier can be used in a browser environment if you first define an import map.
Note: The imported values are read-only views of the features that were exported. Similar to const variables, you cannot re-assign the variable that was imported, but you can still modify properties of object values. The value can only be re-assigned by the module exporting it. See the import reference for an example.
Import maps allow developers to instead specify almost any text they want in the module specifier when importing a module; the map provides a corresponding value that will replace the text when the module URL is resolved.
For example, the imports key in the import map below defines a "module specifier map" JSON object where the property names can be used as module specifiers, and the corresponding values will be substituted when the browser resolves the module URL. The values must be absolute or relative URLs. Relative URLs are resolved to absolute URL addresses using the base URL of the document containing the import map.
With this map you can now use the property names above as module specifiers. If there is no trailing forward slash on the module specifier key then the whole module specifier key is matched and substituted. For example, below we match bare module names, and remap a URL to another path.
It is possible for multiple keys in an import map to be valid matches for a module specifier. For example, a module specifier of shapes/circle/ could match the module specifier keys shapes/ and shapes/circle/. In this case the browser will select the most specific (longest) matching module specifier key.
Import maps allow modules to be imported using bare module names (as in Node.js), and can also simulate importing modules from packages, both with and without file extensions. While not shown above, they also allow particular versions of a library to be imported, based on the path of the script that is importing the module. Generally they let developers write more ergonomic import code, and make it easier to manage the different versions and dependencies of modules used by a site. This can reduce the effort required to use the same JavaScript libraries in both browser and server.
In some JavaScript environments, such as Node.js, you can use bare names for the module specifier. This works because the environment can resolve module names to a standard location in the file system. For example, you might use the following syntax to import the "square" module.
To use bare names on a browser you need an import map, which provides the information needed by the browser to resolve module specifiers to URLs (JavaScript will throw a TypeError if it attempts to import a module specifier that can't be resolved to a module location).
aa06259810