What are Modules and Packages?
As your program grows, keeping all code in one file becomes unmanageable. A Module is simply a file containing Python definitions and statements. A Package is a collection of modules organized in a folder hierarchy. This modularity allows for code reuse and better organization, similar to how you use 'exports' and 'imports' in Flutter or JavaScript.
Importing Modules
You can use any Python source file as a module by executing an import statement in another source file. Python searches for these modules in the current directory, then in the installed libraries path.
Creating Your Own Module
Create a file named calculator.py. This is now a module that can be imported into other files in the same directory.
The Role of init.py
To turn a directory into a Package, it traditionally required a file named __init__.py. While modern Python (3.3+) supports 'Namespace Packages' without it, __init__.py is still used to initialize package-level data or to simplify complex imports.
Standard Library vs. Third-Party
| Category | Source | Examples |
|---|---|---|
| Built-in | Python Core | print(), len(), range() |
| Standard Library | Included with Python | os, sys, json, math, re |
| Third-Party | PyPI (via pip) | requests, flask, tensorflow, pandas |