Sunday, June 14, 2020

Python Module

Python Module


We can consider a module similar to a library of code. This is a file containing a collection of Python functions, Python classes, or variables defined and implemented, that we may want to include in our application. Basically, the modules in Python are normal Python files with a .py extension. The name of the module is exactly the same as the name of the file.

Create a Module


We can create a Python module by simply creating a file with .py extension. For example, save this file as calculator.py 

def add(x, y): 
    return (x+y) 
  
def subtract(x, y): 
    return (x-y) 
    
def mul(x, y): 
    return (x*y) 
  
def div(x, y): 
    return (x/y)

We can use this file as a module in any other .py file using the import statement, for example,

import calculator

print(calculator.add(5, 10))
print(calculator.subtract(5, 10))
print(calculator.mul(5, 10))
print(calculator.div(5, 10))

The function in the module can be accessed by <module_name.function_name>.

Accessing variables in modules


We can access variables from a module in another file (such as lists, sets, tuples, dict, etc). For example, adding the following data to the data.py,

address = {
  "name": "Steve",
  "city": "New York",
  "Street": "123"
  "country": "Ameraica"
}

We can use this data in some other .py file as,

import data

city = data.address["city"]
print(city)
 
#Output
New York

from import Statement


The from .. import .. statement enables us to import specific attributes from a module. The from .. import .. has the following syntax,

from math import sqrt, factorial 

# if we only do "import math", then 
# math.sqrt(25) and math.factorial(7) 
# are needed. 
#but now we can do it simply as
print sqrt(25) 
print factorial(7)