Python packages and modules are a way of structuring Python’s module namespace by using “dotted module names”. A package is simply a way of collecting related modules together within a single tree-like hierarchy.
Very complex applications can be split up into a number of smaller, interconnected pieces using packages and modules, each of which is more manageable and adaptable than a single monolithic block of code.
Here is how we can use packages and modules in Python:
1. You can define functions in a module by creating a new Python file. For example, let’s create a new Python file named `example_module.py` and place the following code in it:
```
def hello_world():
print(“Hello, World!”)
def multiply(a, b):
return a * b
```
1. After you have defined the functions in the module, you can use them in another Python file. Let’s create a new Python file named `main.py` and place following code in it:
```
import example_module
example_module.hello_world()
print(example_module.multiply(2, 3))
```
1. If you want to import a specific function from the module, use the `from` keyword:
```
from example_module import hello_world
hello_world()
```
1. If a module is in a different directory, you might need to add that directory to PYTHONPATH or sys.path at runtime. Alternatively, you can package the module and install it with pip.
A package is simply a directory of Python module(s). For Python to recognize a directory as a package, it must contain a file named `__init__.py`. This file doesn’t have to contain any code; it can be empty.
Below is a simple structure of a package:
```
my_package/
init.py
module1.py
module2.py
```
And you can import modules from your package like:
```
from my_package import module1
from my_package import module2
```