πΈ What is a Package?
- A package is a folder that contains Python files (modules).
- It helps you organize your code.
- You can reuse the code in many projects.
β Why Use Packages?
- Keeps your code clean and structured
- Makes code reusable
- Easy to share with others
π§³ Step-by-Step: Create Your Own Python Package
πΉ Step 1: Create Folder Structure
Letβs say you want a package named mymath
.
mymath/
β
βββ __init__.py
βββ add.py
βββ multiply.py
β
__init__.py
makes this folder a package.
πΉ Step 2: Write Module Files
π add.py
:
def add(a, b):
return a + b
π multiply.py
:
def multiply(a, b):
return a * b
π __init__.py
:
from .add import add
from .multiply import multiply
πΉ Step 3: Use the Package in Your Code
Create a new file outside the folder (for example: main.py
)
π main.py
:
from mymath import add, multiply
print(add(2, 3)) # Output: 5
print(multiply(2, 3)) # Output: 6
β Now your package is working!
πΉ Step 4 (Optional): Add __all__
in __init__.py
This helps when you use from mymath import *
__all__ = ['add', 'multiply']
β Practice Time
Q1: Create a package called greet
with:
hello.py
:hello(name)
β prints βHello, [name]βbye.py
:bye(name)
β prints βGoodbye, [name]β
Answer:
Folder:
greet/
βββ __init__.py
βββ hello.py
βββ bye.py
π hello.py
:
def hello(name):
print(f"Hello, {name}")
π bye.py
:
def bye(name):
print(f"Goodbye, {name}")
π __init__.py
:
from .hello import hello
from .bye import bye
Use it in main.py
:
from greet import hello, bye
hello("John")
bye("John")
π¦ Bonus: Make it Installable (Advanced)
To share with others (like on PyPI), create a setup.py
:
from setuptools import setup, find_packages
setup(
name='mymath',
version='0.1',
packages=find_packages()
)
Then run:
python setup.py install
π§Ύ Summary
Step | What to Do |
---|---|
1 | Create folder and files |
2 | Add __init__.py |
3 | Write code in modules |
4 | Import and use |
π§ Final Tip:
You can create your own Python tools using packages.
Perfect for organizing large projects!
Leave a Reply