Python Packages: Organizing Modules Efficiently
Learn how to create and organize packages in Python. A package is a directory containing multiple modules. Follow the steps to create a package, including setting up folders and necessary files like __init__.py
, and adding your modules.
Python Packages
A package in Python is a way to organize a collection of modules. Physically, a package is a folder containing one or more module files.
Creating a Package
To create a package named mypackage
:
- Create a new folder named
D:\MyApp
. - Inside
MyApp
, create a subfolder namedmypackage
. - Create an empty
__init__.py
file in themypackage
folder. - Create modules
greet.py
andfunctions.py
with the provided code.
Importing from a Package
To use modules from the mypackage
:
Example: Importing from a Package
from mypackage import functions
print(functions.power(3, 2)) # Output: 9
Importing specific functions:
Example: Importing Specific Functions
from mypackage.functions import sum
print(sum(10, 20)) # Output: 30
__init__.py File
The __init__.py
file in a package folder specifies what should be exposed when the package is imported.
Example: __init__.py
from .functions import average, power
from .greet import SayHello
Testing the Package
Create test.py
in D:\MyApp
to test mypackage
:
Example: test.py
from mypackage import power, average, SayHello
SayHello("world")
x = power(3, 2)
print("power(3, 2) : ", x)
Installing a Package Globally
To install mypackage
for system-wide use:
Example: Installing with setup.py
from setuptools import setup
setup(
name='mypackage',
version='0.1',
description='Testing installation of Package',
url='#',
author='author',
author_email='author@email.com',
license='MIT',
packages=['mypackage'],
zip_safe=False
)