Python Modules

Updated: May 18, 2020

A module is a file containing Python definitions and statements. A module can characterize functions, classes and variables. A module can likewise incorporate runnable code. Gathering related code into a module makes the code more clear and use.


def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

Reloading modules in Python

reload() reloads a formerly imported module. This is helpful if we have edited the module source file using an exterior editor and want to attempt out the latest version exclusive of exit the Python interpreter. The return value is the module object.

For Python2.x


For above 2.x and <=Python3.3

import imp


For >=Python3.4

import importlib


Import Model

As we've seen, capability is required just when you use import to bring a module overall. At the point when you utilize the from explanation, you duplicate names from the module to the importer, so the imported names are utilized without qualifying. Here are a couple of more subtleties on the import process.

Import Model Working as:

  • Modules are loaded and run on the first import or from.

  • Running a module’s code creates its top-level names.

  • Later import and from operations fetch an already loaded module.

Python loads, compiles and runs code in a module document just on the primary import, deliberately; since this is a costly activity, Python does it just once per process by default. Also, since code in a module is typically executed once, we can utilize it to introduce variables.


% cat

print 'hey'

maps = 1 # variable

% python

>>> import simple # first import


>>> simple.maps # assignment makes an attribute


>>> simple.maps= 2 # modify attribute in module


>>> import simple # just fetches already-loaded module

>>> simple.maps # code wasn't rerun: attribute unaffected


In Above Example the print and = statements run only the first time the module is imported.

122 views0 comments

Recent Posts

See All

Tell () function can be used to get the position of file handle and returns current position of file object where as Seek () function is used to change the position of the file handle to a given speci

Seek () function is used to change the position of the file handle to a given specific position in python. File handle such as a cursor which defines from where the data has to be read or written in t

Slicing is a Python attitude that enables accessing parts of data from the given sequence like list, tuples etc. A slice object is created based on a set of indices. Slicing starts anywhere from list