Modules are just files that can contain any number of classes, functions and variables. The name of the module is exactly the same as the name of the file, excluding the extension (
.py). Unlike other languages, in Python one does not necessarily define one file per class, and thus the name of the file/module does not need to be the same name as the class. This is a very good reason why the
__init__.py file is necessary when creating packages (tutorial coming soon).
For example, if I were to create a file called
core.py, the module would be called
core. This means that renaming a file could have unintended ripples with the rest of your code-base.
The module can contain executable statements. These statements are intended to initialize the module and are executed only the first time the module name is encountered in an import statement. If you haven't already, I recommend reading about the different ways you can import modules.
Module Variable Scope
The author of a module can use
global variables in the module without worrying about accidental clashes with a userâ€™s global variables. This is because each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module.
To speed up loading modules, Python caches the compiled version of each module in the
__pycache__ directory under the name
module.[version].pyc. For example, my
core.py compiled to
__pycache__/core.cpython-33.pyc. This naming convention allows compiled modules from different releases and different versions of Python to coexist.
Python will always recompile and not store the result when its:
- loaded directly from the CLI.
- There is no source module.
To support a compiled-only distribution of your code, the compiled module must be in the source directory, and there must be a source module. Whilst this may make it more difficult for others to grab your source code, it is not impossible and will not protect you.
Need for Speed
A program's logic doesn't run any faster when it is read from a .pyc file than when it is read from a .py file. The only thing thatâ€™s faster is the speed with which the code is loaded.
Module Variable Scope
The author of a module can use global variables in the module without worrying about accidental clashes with a userâ€™s global variables. This is because each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module.
First published: 16th August 2018