Python Modules
A module in Python is simply a file that groups related code together. Think of it as a reusable toolbox that can contain functions, variables, and even classes. By organizing code into modules, your programs become cleaner, easier to maintain, and reusable across multiple projects.
In practice, any Python file with a .py extension can act as a module.
Creating Your Own Module
To create a module, write your Python code in a file and save it with a .py extension.
Example: create a file named utils.py
Using a Module
Once a module is created, you can use it in another Python file with the import statement.
Example: importing and using the module
Output:
When calling something from a module, always use the format:
module_name.member_name.
Variables Inside a Module
Modules are not limited to functions—they can also store variables such as lists, dictionaries, or constants.
Example: update utils.py
Accessing module variables
Output:
Naming Rules for Modules
• Module names can be anything meaningful
• The file must end with .py
• Avoid using Python reserved keywords
Using an Alias for a Module
Sometimes module names are long or conflict with other names. Python allows
you to rename them during import using as.
Example: module aliasing
Output:
Built-in Python Modules
Python ships with many built-in modules that provide ready-made functionality, such as working with the OS, math operations, or system information.
Example: using the datetime module
Output:
Exploring a Module with dir()
The dir() function helps you inspect what functions and variables are
available inside a module.
Example: listing members of a module
Output:
This works for both built-in modules and user-defined modules.
Importing Specific Members from a Module
If you only need certain parts of a module, you can import them directly using
the from keyword.
Example: module content
Import only what you need
Output:
When using from module import name, you can access name directly without the
module prefix.
