Course
Modules
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Modules
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
The concept of module in Python further enhances the modularity. You can define more than one related functions together and load required functions. A module is a file containing definition of functions, classes, variables, constants or any other Python object. Contents of this file can be made available to any other program. Python has the import keyword for this purpose.
Example
import mathprint ("Square root of 100:", math.sqrt(100))
It will produce the following output
Square root of 100: 10.0
Built in Modules
Python's standard library comes bundled with a large number of modules. They are called built-in modules. Most of these built-in modules are written in C (as the reference implementation of Python is in C), and pre-compiled into the library. These modules pack useful functionality like system-specific OS management, disk IO, networking, etc.
Here is a select list of built-in modules −
User Defined Modules
Any text file with .py extension and containing Python code is basically a module. It can contain definitions of one or more functions, variables, constants as well as classes. Any Python object from a module can be made available to interpreter session or another Python script by import statement. A module can also include runnable code.
Create a Module
Creating a module is nothing but saving a Python code with the help of any editor. Let us save the following code as mymodule.py
def SayHello(name): print ("Hi {}! How are you?".format(name)) return
You can now import mymodule in the current Python terminal.
>>> import mymodule>>> mymodule.SayHello("Harish")Hi Harish! How are you?
You can also import one module in another Python script. Save the following code as example.py
import mymodulemymodule.SayHello("Harish")
Run this script from command terminal
C:\Users\user\examples> python example.pyHi Harish! How are you?
The import Statement
In Python, the import keyword has been provided to load a Python object from one module. The object may be a function, class, a variable etc. If a module contains multiple definitions, all of them will be loaded in the namespace.
Let us save the following code having three functions as mymodule.py.
def sum(x,y): return x+y
def average(x,y): return (x+y)/2
def power(x,y): return x**y
The import mymodule statement loads all the functions in this module in the current namespace. Each function in the imported module is an attribute of this module object.
>>> dir(mymodule)['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'average', 'power', 'sum']
To call any function, use the module object's reference. For example, mymodule.sum().
import mymoduleprint ("sum:",mymodule.sum(10,20))print ("average:",mymodule.average(10,20))print ("power:",mymodule.power(10, 2))
It will produce the following output
sum:30average:15.0power:100
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
The from ... import Statement
The import statement will load all the resources of the module in the current namespace. It is possible to import specific objects from a module by using this syntax. For example −
Out of three functions in mymodule, only two are imported in following executable script example.py
from mymodule import sum, averageprint ("sum:",sum(10,20))print ("average:",average(10,20))
It will produce the following output
sum: 30average: 15.0
Note that function need not be called by prefixing name of its module to it.
The from...import * Statement
It is also possible to import all the names from a module into the current namespace by using the following import statement
from modname import *
This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
The import ... as Statement
You can assign an alias name to the imported module.
from modulename as alias
The alias should be prefixed to the function while calling.
Take a look at the following example
import mymodule as xprint ("sum:",x.sum(10,20))print ("average:", x.average(10,20))print ("power:", x.power(10, 2))
Module Attributes
In Python, a module is an object of module class, and hence it is characterized by attributes.
Following are the module attributes −
__file__
returns the physical name of the module.__package__
returns the package to which the module belongs.__doc__
returns the docstring at the top of the module if any__dict__
returns the entire scope of the module__name__
returns the name of the module
Example
Assuming that the following code is saved as mymodule.py
"The docstring of mymodule"def sum(x,y): return x+y
def average(x,y): return (x+y)/2 def power(x,y): return x**y
Let us check the attributes of mymodule by importing it in the following script
import mymodule
print ("__file__ attribute:", mymodule.__file__)print ("__doc__ attribute:", mymodule.__doc__)print ("__name__ attribute:", mymodule.__name__)
It will produce the following output
__file__ attribute: C:\Users\mlath\examples\mymodule.py__doc__ attribute: The docstring of mymodule__name__ attribute: mymodule
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.
The __name__Attribute
The
__name__
attribute of a Python module has great significance. Let us explore it in more detail.In an interactive shell, __name__ attribute returns '
__main__
'>>> __name__'__main__'
If you import any module in the interpreter session, it returns the name of the module as the
__name__
attribute of that module.>>> import math>>> math.__name__'math'
From inside a Python script, the
__name__
attribute returns '__main__
'#example.pyprint ("__name__ attribute within a script:", __name__)
Run this in the command terminal
__name__ attribute within a script: __main__
This attribute allows a Python script to be used as executable or as a module. Unlike in C++, Java, C# etc., in Python, there is no concept of the main() function. The Python program script with .py extension can contain function definitions as well as executable statements.
Save mymodule.py and with the following code
"The docstring of mymodule"def sum(x,y): return x+y print ("sum:",sum(10,20))
You can see that sum() function is called within the same script in which it is defined.
C:\Users\user\examples> python mymodule.pysum: 30
Now let us import this function in another script example.py.
import mymoduleprint ("sum:",mymodule.sum(10,20))
It will produce the following output
C:\Users\user\examples> python example.pysum: 30sum: 30
The output "sum:30" appears twice. Once when mymodule module is imported. The executable statements in imported module are also run. Second output is from the calling script, i.e., example.py program.
What we want to happen is that when a module is imported, only the function should be imported, its executable statements should not run. This can be done by checking the value of __name__. If it is __main__, means it is being run and not imported. Include the executable statements like function calls conditionally.
Add if statement in mymodule.py as shown
"The docstring of mymodule"def sum(x,y): return x+y
if __name__ == "__main__": print ("sum:",sum(10,20))
Now if you run example.py program, you will find that the sum:30 output appears only once.
C:\Users\user\examples> python example.pysum: 30
The reload() Function
Sometimes you may need to reload a module, especially when working with the interactive interpreter session of Python.
Assume that we have a test module (test.py) with the following function
def SayHello(name): print ("Hi {}! How are you?".format(name)) return
We can import the module and call its function from Python prompt as
>>> import test>>> test.SayHello("Deepak")Hi Deepak! How are you?
However, suppose you need to modify the SayHello() function, such as
def SayHello(name, course): print ("Hi {}! How are you?".format(name)) print ("Welcome to {} Tutorial by TutorialsPoint".format(course)) return
Even if you edit the test.py file and save it, the function loaded in the memory won't update. You need to reload it, using
reload()
function in imp module.>>> import imp>>> imp.reload(test)>>> test.SayHello("Deepak", "Python")Hi Deepak! How are you?Welcome to Python Tutorial by TutorialsPoint
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.