Modules
Modules are files containing Python code. They can define functions, classes, and variables. Python modules are imported using the import
keyword.
Python | |
---|---|
Importing Specific Items
You can import specific items from a module using the from
keyword.
Python | |
---|---|
Aliasing Modules
You can alias a module using the as
keyword.
Python | |
---|---|
Standard Library
Python comes with a standard library that provides a wide range of modules for performing various tasks. You can find the list of standard library modules here.
Third-Party Libraries
In addition to the standard library, Python has a vast ecosystem of third-party libraries that can be installed using package managers like pip
. Some popular third-party libraries include:
- NumPy: For numerical computing.
- pandas: For data manipulation and analysis.
- Matplotlib: For data visualization.
- TensorFlow: For machine learning.
- Django: For web development.
You can find a list of Python packages here.
Creating Your Own Modules
Modules help break down large programs into smaller, more manageable pieces. You can create your own modules by defining functions, classes, and variables in a Python file.
For example, let's say you have the following directory structure:
mymodule.py | |
---|---|
main.py | |
---|---|
When you import your own modules from another file, the module has to be in the same directory as the file you are importing it from.
Setting Up a Directory as a Module
The __init__.py
file is used to mark a directory as a Python package. It can be empty or contain initialization code if necessary. For example, let's say you have a directory named mypackage
with the following structure:
To import the mypackage
directory as a module, you can use the following syntax:
Then, you can import the mypackage
module in your main.py
file as follows:
main.py | |
---|---|
Summary
Modules allow you to import different pieces of code and structure large projects.