Modules in Python

Modules in Python

In Python, modules are files that contains a number of functions that may be used in several files. Instead of writing a piece of code in several files that require the same functionality, a separate file can be created containing the code and the file can be imported in any file that desires to use it.

 

 

Create Modules in Python

A module can be created with any name as long as it has .py extension in the end.

Example:

 

# Python program to exemplify module creation

def Func():
  print("StudyExperts!")

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

var_int = 1000

In the module provided above, two functions and a variable have been defined. Function named “func” just prints “StudyExperts!” upon invocation. Function named “Function” takes two parameters and returns their sum to the calling program. Variable named “var_int” is initialized to 1000.

 

 

Use a Module

To use a module in your python script, it has to be included in it. It is done using the keyword import followed by the name of the module. If the module and the script are kept in the same folder, then the above mentioned way can be used to include the module. But if they are in different folders, then path must be shown in the script. After including the import statement with the module name, definitions of functions, classes, variables, etc can be used by using their names prefixed by module name and a dot.

Example:

 

# Python program to exemplify using a module 

import MyModule
MyModule.Func()

Output:

StudyExperts!

 

 

Re-naming a Module

A module can be renamed by using the keyword as and the new module name, after the import statement. All the functions, classes, etc can the be used by using the new name of the module, name of the component and a dot between them.

Example:

 

# Python program to exemplify re-naming a module 

import MyModule as module
module.Func()

Output:

StudyExperts!

 

 

Import from Module

Instead of importing the whole module in your current script, some part of it that you want to be used can be imported. It is done using the from and import keywords.

Example:

 

# Python program to exemplify importing from a module 

from MyModule import Function, var_int
x = Function(15, 10)
print(x)
print(var_int)

Output:

25
1000

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *