Packages help organize your Python code into folders so it is easier to find and reuse.
0
0
Package structure and usage in Python
Introduction
You want to group related Python files together in one folder.
You want to reuse code across different projects by importing it easily.
You want to avoid name conflicts by separating code into different packages.
You want to share your code with others as a package.
You want to keep your project organized as it grows bigger.
Syntax
Python
package_name/
__init__.py
module1.py
module2.py
# To use a module from the package:
from package_name import module1
module1.some_function()The __init__.py file tells Python this folder is a package.
You import modules from the package using from package_name import module.
Examples
This example shows a package named
my_package with one module greetings.py. We call the say_hello function from it.Python
my_package/
__init__.py
greetings.py
# greetings.py content:
def say_hello():
print('Hello!')
# Using the package:
from my_package import greetings
greetings.say_hello()This example shows a package
utils with two modules. We import both and use their functions.Python
utils/
__init__.py
math_tools.py
string_tools.py
# math_tools.py content:
def add(a, b):
return a + b
# string_tools.py content:
def shout(text):
return text.upper() + '!'
# Using the package:
from utils import math_tools, string_tools
print(math_tools.add(3, 4))
print(string_tools.shout('hi'))Sample Program
This program shows how to create a package my_package with a module greetings. Then it imports and uses the say_hello function.
Python
# Folder structure: # my_package/ # __init__.py # greetings.py # greetings.py content: def say_hello(): print('Hello from the package!') # main.py content: from my_package import greetings greetings.say_hello()
OutputSuccess
Important Notes
Every folder that should be a package needs an __init__.py file, even if it is empty.
You can import specific functions or classes from modules inside packages for cleaner code.
Packages help keep your project tidy and make code sharing easier.
Summary
Packages are folders with Python files and an __init__.py file.
Use packages to organize and reuse your code easily.
Import modules from packages using from package_name import module.