Modules and Packages in Python
Understanding Python modules and packages: how to organize code, import functionality, create reusable files, and structure large applications.
What is a Module?
In Python, every .py file is a module. Modules help organize code into separate files and allow reuse across projects.
1. Creating and Importing a Module
Creating your own module and importing it.
Different Import Styles
Import statements allow flexibility in how we access module contents.
1. Import Specific Functions
Import only what you need.
2. Import with Alias
Using shorter names.
Built-in Modules
The Python Standard Library provides powerful modules ready to use.
1. Using Built-in math Module
Example using math module.
__name__ Special Variable
Every Python module has a special variable called __name__. It tells whether the file is run directly or imported.
1. Using if __name__ == "__main__"
Prevent code from running on import.
What is a Package?
Packages help organize multiple related modules inside directories.
1. Basic Package Structure
Folder-based organization.
Importing from Packages
You can import modules or functions from inside a package.
1. Import Example
Importing from package.
Importing from Parent or Multiple-Level Folders
Unlike JavaScript, Python does not directly support relative path imports like "../.." in scripts. Instead, Python uses package-based imports and the module search path (sys.path). There are three proper ways to handle multi-level imports.
1. Proper Project Structure (Recommended)
Use packages instead of path hacks.
2. Absolute Import (Best Practice)
Import using full package path.
3. Relative Imports (Inside Packages Only)
Using dot notation for current, parent, and multiple parent folders.
4. Modifying sys.path (Not Recommended for Production)
Manual multi-level folder import.
5. Best Practice Summary
How professionals handle multi-level imports.
Installing Third-Party Packages
Most real-world Python applications rely on external libraries. These libraries are hosted on PyPI (Python Package Index). Python uses pip as its official package manager to install and manage them. In this section, we will learn how to properly work with third-party packages in a safe and professional way.
1. Installing a Package
Install a library from PyPI using pip.
2. Using requirements.txt
Save and reinstall project dependencies easily.
3. Deleting (Uninstalling) a Package
Remove an installed package from your environment.
4. Upgrading a Package
Update a package to the latest available version.
5. Virtual Environments (Highly Recommended)
Isolate dependencies for each project.
6. Best Practices
Professional recommendations for managing third-party packages.