Understanding Python Modules
Python modules are the fundamental building blocks of Python programs. A module is a file containing Python definitions and statements. It provides a way to organize and reuse code, making it easier to develop and maintain larger applications.
What is a Python Module?
A Python module is a single file, typically with a .py
extension, that contains a collection of functions, classes, and variables. Modules allow you to organize your code into logical units, making it easier to manage and reuse.
Importing Modules
To use the functionality provided by a module, you need to import it. Python provides several ways to import modules:
## Import the entire module
import module_name
## Import specific functions or classes from a module
from module_name import function_name, class_name
## Import all functions and classes from a module
from module_name import *
Accessing Module Contents
Once you have imported a module, you can access its contents using the dot notation:
## Access a function from the module
module_name.function_name()
## Access a class from the module
module_object = module_name.class_name()
Built-in Modules
Python comes with a rich set of built-in modules that provide a wide range of functionality, such as file I/O, networking, and data manipulation. Some examples of built-in modules include os
, sys
, math
, and datetime
.
import os
print(os.getcwd()) ## Get the current working directory
import sys
print(sys.version) ## Get the Python version
Creating Custom Modules
You can create your own custom modules by writing Python code in a .py
file. These modules can then be imported and used in your Python programs.
## my_module.py
def greet(name):
print(f"Hello, {name}!")
## main.py
import my_module
my_module.greet("Alice")
By understanding the basics of Python modules, you can organize your code effectively and reuse functionality across your projects.