python modules and packages

module intro

  • python module is a python file contains a set of functions, variables and classes
  • modules are a way to organize the code based on the type of the functionality
  • improves the project structure and maintainability
  • improves code reusability

module usage

  • create a file named calculator.py with basic math functionalities.

calculator.py

pi = 3.14

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b
  • we can use the functions in the above module in another module.
  • let's create a new module named main.py and use the module calculator

main.py

import calculator

print(calculator.add(10, 20))
# output: 30
print(calculator.pi)
# output: 3.14
  • If we don't want to import complete module then we can import the required functions, variables, etc. using keywords from and import

Let's see the code for that

from calculator import add, pi

print(add(10, 20))
# output: 30
print(pi)
# output: 3.14

in-built python modules

package intro

  • A python package is a directory which collection of modules.
  • Modules that are related to each other are mainly put in the same package.
  • When a module from an external package is required in a program, that package can be imported and its modules can be put to use.
  • Package can contain a special file named __init__.py which distinguishes a package from a directory

When you import a package, only the methods and the classes in the __init__.py file of that package are directly visible.

package usage

  • Lets create a package named calci which contains modules like basic.py and advanced.py
  • The package directory looks something like this
.
├── calci
│   ├── __init__.py
│   ├── advanced.py
│   └── basic.py
└── main.py
  • basic.py module contains functions like add, multiply, etc.
  • advanced.py modules contains functions like celsius_to_fahrenheit, fahrenheit_to_celsius

calci/advanced.py

def celsius_to_fahrenheit(celsius):
      fahr = (float(celsius) * 1.8) + 32
      return fahr

def fahrenheit_to_celsius(fahrenheit):
    celsius = (5 / 9 * fahrenheit - 32)
    return celsius

calci/basic.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

main.py

from calci.advanced import celsius_to_fahrenheit
from calci.basic import add

print(add(10, 20))
# output: 30
print(celsius_to_fahrenheit(10))
# output: 50.0
  • when we run the module main.py it gives the ouptput.
  • packages are very useful when we have reusable functionality.

in-built python packages