Utilizing Python Modules and Packages
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 274 wordsExplore the use of Python modules and packages to organize your code, including creating and importing custom modules and understanding the Python Package Index (PyPI).
Modules and packages are essential for organizing and reusing your code. This guide covers creating and importing custom modules and understanding the Python Package Index (PyPI).
Create a module by saving a Python file with functions and variables.
# my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14
Import and use your custom module.
import my_module
print(my_module.greet("Alice"))
print(my_module.PI)
Modules can include any Python code, including classes and constants.
# my_module.py
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
MY_CONSTANT = 42
A package is a directory with an __init__.py
file.
# my_package/
# __init__.py
# module1.py
# module2.py
# module1.py
def func1():
return "Function 1"
# module2.py
def func2():
return "Function 2"
The __init__.py
file can be used to initialize the package and define what gets imported.
# my_package/__init__.py
from .module1 import func1
from .module2 import func2
from my_package import func1, func2
print(func1())
print(func2())
PyPI is a repository of software for the Python programming language. You can install packages from PyPI using pip
.
pip install requests
To create and distribute your own package on PyPI, follow these steps:
setup.py
file with your package details.from setuptools import setup, find_packages
setup(
name='my_package',
version='0.1',
packages=find_packages(),
install_requires=[],
)
python setup.py sdist bdist_wheel
twine upload dist/*
Modules and packages help you organize and reuse your code effectively. Practice creating custom modules and exploring packages on PyPI to enhance your Python projects.