
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialWe already know that a module is a file containing definition of functions, classes, variables, constants or any other Python object, even some executable code. Standard distribution of Python contains a large number of modules, generally known as built-in modules. These built-in modules may be written in C and integrated with Python interpreter, or a Python script (with .py extension). In this chapter we shall learn to build a custom Python module and use its functions in other programs.
Any text file with .py extension and containing Python code is a module. Just as in built-in modules, different Python objects in a custom module can be imported in interpreter session or another script.
If the program has a large number of functions and classes, they are logically organised in separate modules. One module stores classes, functions and other resources of similar relevance or developed for similar purpose. Such a modular design of the code is easy to understand, use and maintain.
Shown below is a Python script (messages.py) containing definition of a couple of functions.
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
We can now import this module and execute its functions from Python prompt
>>> import messages
>>> messages.welcome("Ravi")
Hi Ravi. Welcome to Python Tutorial
>>> messages.bye("Ravi")
Good Bye Ravi. See you again
Use as keyword to refer to a module by an alias name.
>>> import messages as msg
>>> msg.welcome("Amar")
Hi Amar. Welcome to Python Tutorial
When you import a module, all resources defined in it are loaded in current namespace. You may choose to load specific function(s) from the module using from..to syntax. This will not load other unwanted functions.
>>> from messages import welcome
>>> welcome("Rama")
Hi Rama. Welcome to Python Tutorial
>>> bye("Rama")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
bye("Rama")
NameError: name 'bye' is not defined
Here only 'welcome()' function gets loaded from messages module. Hence calling 'bye()' function raises NameError. Note that function need not be called by prefixing name of its module to it.
There is also another alternative syntax available – 'from module import *' which is effectively equivalent to importing entire module (import module)
As mentioned earlier, functions in Python module can be imported in another. We try to access welcome() function in messages module from following script (moduletest.py)
import messages
name=input('enter name:')
messages.welcome(name)
Run 'moduletest.py' to get following output:
enter name:MurliMohan
Hi MurliMohan. Welcome to Python Tutorial
Every Python resource is object. Likewise every module, either built-in or custom, is object of module class.
>>> #built-in module
>>> import math
>>> type(math)
<class 'module'>
>>> #custom module
>>> import messages
>>> type(messages)
<class 'module'>
A module object is characterized by various attributes. Attribute names are prefixed and post-fixed by double underscore __. Here are some important attributes:
__name__ :
When Python is running in interactive mode or as a script, it sets value of this special variable to '__main__'. It is the name of scope in which top level is being executed.
>>> __name__
'__main__'
From within a script also, we find value of __name__ attribute is set to '__main__'. Execute following script.
'module docstring'
print ('name of module:',__name__)
Output:
name of module: __main__
However, for imported module this attribute is set to name of the Python script. (excluding the extension .py). For messages.py module
>>> import messages
>>> messages.__name__
'messages'
However, this can be modified by assigning different string to this attribute.
>>> messages.__name__='mymessages'
>>> messages.__name__
'mymessages'
As seen earlier, value of __name__ is set to __main__ for top level module. However, for imported module it is set to name of file. Run following script (moduletest.py)
import messages
print ('name of top level module:', __name__)
print ('name of imported module:', messages.__name__)
Output:
name of top level module: __main__
name of imported module: messages
A Python script containing function may also have a certain executable code. Hence if we import it its code will be run automatically. To messages.py we add some executable code as below:
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
name=input('enter name:')
bye(name)
Now we if we run the moduletest.py script, We'll find that the input statement and call to welcome() will be executed.
c:\python37>python moduletest.py
Output:
enter name:Kamala
Good Bye Kamala. See you again
enter name:mohan
Hi mohan. Welcome to Python Tutorial
This is output of both the scripts. What if we just want to import function from messages module and run executable code in it?
This is where the fact that value of __name__attribute of top level script is __main__ is useful. Change messages.py script such that it executes input and function call statement only if __name__ is equal to __main__.
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
if __name__=='__main__':
name=input('enter name')
bye(name)
The moduletest.py is run unchanged. Executable part in imported messages module won't run now.
enter name: mohan
Hi mohan. Welcome to Python Tutorial
Note that you can always run messages.py script independently.
__doc__:
This attribute returns the docstring of module. Just as in function, Documentation string (docstring) is a string literal in first line written in module code. In messages.py module
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
if __name__=='__main__':
name=input('enter name')
bye(name)
The __doc__ attribute will return string defined at the beginning of module code.
>>> messages.__doc__
'docstring of messages module'
__file__:
This attribute will returns the name and path of the module file.
>>> messages.__file__
'C:\\python37\\messages.py'
__dict__:
This attribute returns a dictionary object of all attributes, functions and other definitions and their respective values.
>>> dct=messages.__dict__
>>> dct['__doc__']
'docstring of messages module'
>>> dct['__name__']
'messages'
>>> dct['__file__']
'C:\\python36\\messages.py'
>>> dct['bye']
<function bye at 0x000001B227E0D158>
>>> dct['welcome']
<function welcome at 0x000001B225701E18>
dir() is a built-in function that also returns list of all attributes and functions in a module.
>>> dir('messages')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
How does Python interpreter find a module when a script requests it to be imported? Python follows following method to locate a module:
The sys.path attribute holds all locations to be searched for module.
>>> import sys
>>> sys.path
['', 'C:\\python37\\Lib\\idlelib', 'C:\\python37\\python37.zip', 'C:\\python37\\DLLs',
'C:\\python37\\lib', 'C:\\python37', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\python37\\lib\\site-packages']
If the module is not present in any of directories in the path, ModuleNotFoundError is raised.
Python loads any module only once even if import statement is issued repeatedly. Consider following messages.py script:
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
welcome("world")
bye("world")
Let us import messages module from Python prompt. The calls to functions in the code also get executed. However, repeating import statement doesn't execute them again.
>>> import messages
Hi world. Welcome to Python Tutorial
Good Bye world. See you again
>>> import messages
>>>
Now suppose we need to modify the SayHello() function before executing it again. Updated function is :
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to Python Tutorial".format(name))
return
def bye(name):
print ("Good Bye {}. See you again".format(name))
welcome("Guest")
bye("Guest")
This change will be effected only if current interpreter session is closed and re-launched. If such changes are to be done frequently, to close and restart Python is cumbersome. In order to call load the module without terminating interpreter session, use reload() function from imp module.
>>> import imp
>>> imp.reload(messages)
Hi Guest. Welcome to Python Tutorial
Good Bye Guest. See you again
<module 'messages' from 'C:\\python37\\messages.py'>
In this chapter we learned how to build a custom module and import functions from it into other module.