Python modules

 A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.

The import statement - when the interpreter encounters an import statement, it imports the module. of the module is present in the search bath. A search bath is a list of directories that the interpreter searched for importing a module.

Example- create a simple calc.py module, in which we define two functions, one add and another subtract

def add (x, y):

return (x+y)

def subtract (x, y):

return (x-y)

Now, to import the module calc⋅py, we need to put the following command at the top of the script-

Syntax-import module

import calc

print (calc.add (10,2))

The from statement- Python's from statement is use to import specific attributes from a module without

importing the module as a whole.

Example - from math import sqrt, factorial

 print (sqrt (16))

 print (factorial (6))

Import all names- The * symbol used with the import statement is used to import all the names from a

module to a current namespace.

Syntax- from module_name import *

Example - from math import *

 print (sqrt (16))

 print (factorial (6))

Locating Python modules - when we import a module in Python, the interpreter searches for the module

in following manner-

 First, it searches for the module in the current directory.

 If the module isn't found in the current directory, Python then searches each directory in the shell variable PYTHONPATH.

 If that also fails, Python checks the installation- dependent list of directories configured at the time Python is installed.

Directories list for Modules- sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search for the required module.

Example- import sys

 print (sys.path)

Renaming the Python module- You can rename the module while importing it using the Keyword.

Syntax- import module_name as alias name

Example- import math as mt

 print (mt.sqrt (16))

Comments

Popular posts from this blog

Machine learning

Python libraries