How to Create Your Own Python Package (Step-by-Step Guide)



πŸ”Έ 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

StepWhat to Do
1Create folder and files
2Add __init__.py
3Write code in modules
4Import and use

🧠 Final Tip:

You can create your own Python tools using packages.
Perfect for organizing large projects!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *