Intern
What is a module in Python?
sobes.tech AI
Answer from AI
A module is a file containing definitions and instructions in Python. It allows organizing code, making it more structured, reusable, and understandable. Modules have the extension .py.
Main advantages of using modules:
- Code organization: Breaking a large program into smaller, manageable files.
- Reusability: The ability to import and use functions, classes, and variables defined in another module.
- Name isolation: Each module has its own namespace, preventing name conflicts.
Modules are imported using the import keyword.
# Importing an entire module
import math
# Using a function from the imported module
print(math.sqrt(16))
You can import specific objects from a module:
# Importing a specific function
from math import sqrt
# Using the imported function directly
print(sqrt(25))
There are different types of modules:
- Built-in modules: Part of Python's standard library (e.g.,
math,os,sys). - User-defined modules: Created by developers for specific projects.
- Third-party modules: Installed via package managers (e.g.,
pip) (e.g.,requests,django).
A module's namespace is accessible via <module_name>.<object_name>.
import math
# Accessing a constant from the math module
print(math.pi)
When a module is imported, Python executes its code. If the module is imported again within the same session, its code is not executed again; the already loaded object is used.
# my_module.py
print("My_module loaded")
def greet(name):
print(f"Hello, {name}!")
# main.py
import my_module # Will print "My_module loaded"
my_module.greet("World")
import my_module # Will not print anything, as the module is already loaded
A module can be reloaded using the reload function from the importlib module (Python 3+).
# importlib.reload(module_name)