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


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

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


import mymodule                  

Output: Hello Freshersnow

Renaming Module

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


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

Output: jeans

Built-in Modules

There are several built-in modules.


import platform   
x = platform.system()    

Use the dir( ) function

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


import platform         
x = dir(platform)          

Output: windows

import from module

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

Syntax: from modname import *


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.