6 2 Creating Modules Explained
Key Concepts
Creating modules in Python involves several key concepts:
- Defining a Module
- Importing a Module
- Using Functions and Variables from a Module
- Module Search Path
- Executing Modules as Scripts
1. Defining a Module
A module in Python is a file containing Python definitions and statements. The file name is the module name with the suffix .py
appended.
Example:
# my_module.py def greet(name): return f"Hello, {name}!" PI = 3.14159
Analogy: Think of a module as a toolbox containing various tools (functions and variables) that you can use in your projects.
2. Importing a Module
To use the functions and variables defined in a module, you need to import the module. This is done using the import
statement.
Example:
import my_module print(my_module.greet("Alice")) # Output: Hello, Alice! print(my_module.PI) # Output: 3.14159
Analogy: Importing a module is like taking a specific toolbox from a storage room to your workbench.
3. Using Functions and Variables from a Module
Once a module is imported, you can access its functions and variables using the dot notation.
Example:
import my_module greeting = my_module.greet("Bob") print(greeting) # Output: Hello, Bob! radius = 5 area = my_module.PI * radius ** 2 print(area) # Output: 78.53975
Analogy: Using functions and variables from a module is like selecting specific tools from the toolbox to perform a task.
4. Module Search Path
When you import a module, Python searches for the module in a list of directories. This list is stored in the sys.path
variable.
Example:
import sys print(sys.path)
Analogy: The module search path is like a map that guides Python to find the toolbox (module) in various storage rooms (directories).
5. Executing Modules as Scripts
You can execute a module as a script by running it directly. This is useful for testing and debugging. The __name__
variable helps determine if the module is being run as a script.
Example:
# my_module.py def greet(name): return f"Hello, {name}!" if __name__ == "__main__": print(greet("Alice"))
Analogy: Running a module as a script is like using the toolbox to perform a specific task directly, rather than just having it available for future use.
Putting It All Together
By understanding and using modules effectively, you can organize your code into reusable and manageable pieces. Modules are a fundamental aspect of Python programming that enhance code maintainability and reusability.
Example:
# my_module.py def greet(name): return f"Hello, {name}!" PI = 3.14159 if __name__ == "__main__": print(greet("Alice")) # main.py import my_module print(my_module.greet("Bob")) # Output: Hello, Bob! print(my_module.PI) # Output: 3.14159