Python Modules

Python Modules: It is an object with arbitrarily named attributes that you can bind and reference. Python module can define functions, classes, and variables. Grouping related code into a module makes the code easier to understand and use. And the module is a Python object with arbitrarily named attributes that you can bind and reference.



Python Modules

Create Module

If you want to create a module just save the file name with mymodule.py

Example

def greeting(name):                   
print ("Hello, " + name)

Use Module: By using an import statement you can use modules.

Example

import mymodule                  
mymodule.greeting("Freshersnow")

Output: Hello Freshersnow

Renaming Module

We can create an alias when you import a module, by using them as a keyword.

Example

import mymodule as mx             
a = mx.person1["dress"]             
print(a)

Output: jeans

Built-in Modules

There are several built-in modules.

Example

import platform   
x = platform.system()    
print(x)

Use the dir( ) function

There is one directory function which will be listed all the function names in one module.

Example

import platform         
x = dir(platform)          
print(x)

Output: windows

import from module

If you want anything, we can import them by using ‘from’ keyword.

Syntax: from modname import *

Example

def greeting(name):         
print("Hello, " + name)        
person1 = {   "name": "Merry","age": 34,"country": "Australia"  }     
from mymodule import person1     
print (person1["age"])

Output: 36

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences −

  • The current directory.
  • While the module isn’t found, Python then searches each directory in the shell variable PYTHONPATH.
  • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.