A Module in Python is simply a file containing Python code (functions, classes, or variables). A Package is a directory that contains multiple modules and a special __init__.py file.
Using modules and packages allows you to organize your code, reuse it, and keep things clean.
Basic Concepts
- Module: A single
.pyfile (e.g.,calculator.py). - Package: A folder of
.pyfiles (e.g., amath_toolsfolder). - Library: A collection of packages (often used interchangeably with package).
1. Basic Module Import
You can import built-in modules using the import keyword.
import math
result = math.sqrt(25)
print(result)
Output:
5.0
2. Import Specific Functions
If you only need one or two things from a module, you can import them directly.
from math import pi, sqrt
print(pi)
print(sqrt(16))
Output:
3.141592653589793
4.0
3. Rename a Module (Aliasing)
You can give a module a shorter name to save typing.
import math as m
print(m.factorial(5))
Output:
120
4. Rename a Specific Function
You can also alias individual functions.
from math import factorial as fact
print(fact(4))
Output:
24
5. Import All Functions (Not Recommended)
Using * imports everything, meaning you don't need to type the module name. (This is generally avoided because it can cause naming conflicts).
from math import *
print(pow(2, 3))
Output:
8.0
6. Create Your Own Module
Imagine you create a file named greetings.py:
# File: greetings.py
def say_hello(name):
return f"Hello, {name}!"
Now, in your main file:
import greetings
print(greetings.say_hello("Ram"))
Output:
Hello, Ram!
7. Variables in Modules
Modules can contain variables, dictionaries, and lists too.
# File: config.py
database_url = "localhost:5432"
admin_user = "admin"
In your main file:
import config
print(config.database_url)
Output:
localhost:5432
8. The dir() Function
Use dir() to see all the functions and variables defined inside a module.
import math
print(dir(math)[:5]) # Showing just the first 5 for brevity
Output:
['__doc__', '__loader__', '__name__', '__package__', '__spec__']
9. Finding Module Location
You can find out where a module's file is stored on your computer using __file__.
import random
print(random.__file__)
Output: (Will look similar to this)
/usr/lib/python3.10/random.py
10. Creating a Package
To create a package, create a folder and put a __init__.py file inside it.
my_store/
__init__.py
products.py
payments.py
11. Importing from a Package
from my_store import products
# Assuming products.py has a get_laptops() function
products.get_laptops()
12. Importing a Specific Function from a Package
from my_store.payments import process_credit_card
process_credit_card(5000)
13. The __init__.py File
This file tells Python that the directory should be treated as a package. It can be completely empty, or it can contain initialization code that runs automatically when the package is imported.
14. Sub-packages
Packages can contain other packages.
my_store/
__init__.py
billing/
__init__.py
invoices.py
Importing from it:
from my_store.billing import invoices
15. Standard Library: random
Python comes with many pre-installed modules.
import random
choices = ["Rock", "Paper", "Scissors"]
print(random.choice(choices))
Output:
Paper
16. Standard Library: datetime
import datetime
now = datetime.datetime.now()
print(now.year)
Output:
2026
17. Standard Library: os
Used for interacting with your operating system (like creating folders).
import os
print(os.getcwd()) # Gets current working directory
Output:
/home/user/python_projects
18. Understanding sys.path
When you import a module, Python looks for it in specific directories. You can see these directories using sys.path.
import sys
for path in sys.path[:3]:
print(path)
19. The Special __name__ Variable
Every module has a built-in variable called __name__. If you run a script directly, its __name__ is "__main__". If you import it, its __name__ is the file's actual name.
# File: calculator.py
print(f"The name of this module is: {__name__}")
If you run calculator.py directly: Output:
The name of this module is: __main__
20. The if __name__ == "__main__": Trick
This prevents code from running automatically when you import a module.
# File: helper.py
def do_work():
print("Working...")
# This block ONLY runs if you execute helper.py directly.
# It will NOT run if you type `import helper` in another file.
if __name__ == "__main__":
print("Running directly!")
do_work()
21. Third-Party Packages (pip)
Not all packages come with Python. You install external ones using your terminal:
pip install requests
Then you can use them:
import requests
22. Restricting * Imports with __all__
If someone uses from module import *, you can control exactly what they get by defining __all__.
# File: secret_math.py
__all__ = ["add"] # Only 'add' gets exported during a * import
def add(a, b): return a + b
def subtract(a, b): return a - b
23. Circular Imports (A Common Error)
If Module A imports Module B, and Module B imports Module A, Python will get confused and throw an error. Fix: Move the shared code to a third module, or move the import statement inside your functions.
24. Relative Imports
Inside a package, you can use dots to import sibling modules.
.: current folder..: parent folder
# Inside my_store/payments.py
from . import products # Imports products.py from the same folder
25. Reloading a Module
If you change a module's code while a Python shell is running, importing it again won't do anything because Python caches it. You must force a reload.
import importlib
import my_module
# You edit my_module.py and save it...
importlib.reload(my_module) # Forces Python to fetch the new code
Module vs Package Summary
- Module → A single file (
math.py). Use it to group related functions. - Package → A folder of modules with an
__init__.py. Use it to group related modules. - Library → Often refers to a large package published online (like
pandasornumpy).
Easy way to remember:
import x→ Brings in the whole toolbox.from x import y→ Brings in just one tool.import x as z→ Brings in the toolbox but puts a nickname on it.