Contents
Roadmap info from roadmap website
Modules
Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: example.py
, is called a module, and its module name would be example. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.
Visit the following resources to learn more:
Characteristic | Description |
---|---|
Definition | A module is a Python file (.py) containing definitions, functions, classes, and variables that can be reused in other Python scripts. |
File Extension | Modules are typically Python files with the .py extension (e.g., module_name.py ). |
Importing Modules | Modules are imported using the import statement (e.g., import module_name ). |
Namespace | Each module creates its own namespace, meaning that module contents do not conflict with other code. |
Accessing Module Contents | After importing, module contents are accessed using dot notation (e.g., module_name.function_name() ). |
Built-in Modules | Python comes with many built-in modules (e.g., os , sys , math , datetime ), which provide a wide range of functionalities. |
Standard Library | The Python Standard Library is a collection of modules that provide standardized solutions for many programming tasks. |
Custom Modules | You can create your own modules by writing Python code in a .py file and importing it into other scripts. |
Package | A package is a collection of modules in a directory that contains an __init__.py file. It allows for the organization of related modules. |
Relative Imports | Modules within a package can be imported relatively (e.g., from . import module_name ). |
Re-importing | Re-importing a module using import does not reload it. To reload a module, use the importlib.reload(module_name) function. |
Third-Party Modules | Python allows the use of third-party modules, which can be installed via package managers like pip . |
Compiled Modules | Modules can also be compiled (e.g., .pyc files) for faster loading, though this is usually handled automatically by Python. |
Module Caching | When a module is imported, it is cached in sys.modules and subsequent imports use the cached version unless it is explicitly reloaded. |
name Variable | The special variable __name__ in a module is set to "__main__" if the module is run as the main program, or to the moduleβs name if imported. |
Documentation | Modules should include docstrings at the top of the file to describe their purpose and usage. These can be accessed using help(module_name) . |