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.

120 views0 comments

Recent Posts

See All

Command Line Arguments in Python

Command Line Arguments are the arguments that are specified after the name of the program in the command line shell of the operating system. Python gives different ways of dealing with these types of