Document 4
Document 4
They
are essentially Python files (.py) containing definitions (like functions,
classes, and variables) that you can use in other Python files or in the
interactive interpreter. This promotes modularity, making your code cleaner,
more manageable, and easier to maintain.Creating a ModuleCreating a
module is as simple as writing Python code and saving it with a .py
extension. The filename becomes the module's name.Let's create a simple
module. Imagine a file named myutils.py:Python
# myutils.py
PI = 3.14159
def greet(name):
"""Returns a greeting message."""
return f"Hello, {name}! Welcome."
class Calculator:
def multiply(self, x, y):
return x * y
In this myutils.py file, we've defined a constant PI, two functions (greet and
add), and a class Calculator. This file is now a module named myutils.
Importing a Module
Once a module is created (and Python can find it – typically in the same
directory as your script, or in a directory listed in Python's search path like
sys.path), you can import its contents into another Python script or session.
There are several ways to do this:
calc = myutils.Calculator()
print(calc.multiply(4, 5)) # Output: 20
2.from module_name import specific_item1, specific_item2: This
imports specific items directly into the current script's namespace. You can
then use them without the module name prefix.
Python
# main_script.py
from myutils import greet, PI
print(PI) # Output: 3.14159
message = greet("Bob")
print(message) # Output: Hello, Bob! Welcome.
# add and Calculator are not directly imported, so this would error:
# print(add(1, 2))
# To use them, you'd need to import them or use the module prefix.
from module_name import *: This imports all public names (those not
starting with an underscore) from the module into the current namespace.
While convenient for small modules or interactive sessions, it's generally
discouraged in larger projects because it can lead to name collisions (where
names in your script unintentionally clash with names from the module) and
make it harder to trace where a function or variable originated.
Python
# main_script.py
from myutils import *
print(PI)
print(greet("Charlie"))
print(add(10, 20))
my_calc = Calculator()
print(my_calc.multiply(2, 3))
import module_name as alias: This imports the entire module but gives it
a shorter or more convenient alias. This is useful for long module names or
to avoid naming conflicts.
Python
# main_script.py
import myutils as mu
print(mu.PI)
print(mu.greet("Dave"))
Python
from myutils import greet as welcome_message
print(welcome_message("Eve"))
Modules help in creating reusable and organized code. When your script
executes an import statement, Python searches for the module in a list of
directories (including the current directory and standard library locations)
and executes the module's code once to make its definitions available.