SlideShare a Scribd company logo
1 of 4
Download to read offline
http://www.tutorialspoint.com/python/python_modules.htm Copyright © tutorialspoint.com
PYTHON MODULES
A module allows youto logically organize your Pythoncode. Grouping related code into a module makes the
code easier to understand and use. A module is a Pythonobject witharbitrarily named attributes that youcanbind
and reference.
Simply, a module is a file consisting of Pythoncode. A module candefine functions, classes and variables. A
module canalso include runnable code.
Example:
The Pythoncode for a module named aname normally resides ina file named aname.py. Here's anexample of a
simple module, support.py
def print_func( par ):
print "Hello : ", par
return
The import Statement:
Youcanuse any Pythonsource file as a module by executing animport statement insome other Pythonsource
file. The import has the following syntax:
import module1[, module2[,... moduleN]
Whenthe interpreter encounters animport statement, it imports the module if the module is present inthe search
path. A searchpathis a list of directories that the interpreter searches before importing a module. For example,
to import the module hello.py, youneed to put the following command at the top of the script:
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
Whenthe above code is executed, it produces the following result:
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module
executionfromhappening over and over againif multiple imports occur.
The from...import Statement
Python's from statement lets youimport specific attributes froma module into the current namespace. The
from...import has the following syntax:
from modname import name1[, name2[, ... nameN]]
For example, to import the functionfibonaccifromthe module fib, use the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces the item
fibonaccifromthe module fib into the globalsymboltable of the importing module.
The from...import * Statement:
It is also possible to import allnames froma module into the current namespace by using the following import
statement:
from modname import *
This provides aneasy way to import allthe items froma module into the current namespace; however, this
statement should be used sparingly.
Locating Modules:
Whenyouimport a module, the Pythoninterpreter searches for the module inthe following sequences:
The current directory.
If the module isn't found, Pythonthensearches eachdirectory inthe shellvariable PYTHONPATH.
If allelse fails, Pythonchecks the default path. OnUNIX, this default pathis normally
/usr/local/lib/python/.
The module searchpathis stored inthe systemmodule sys as the sys.path variable. The sys.pathvariable
contains the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable:
The PYTHONPATH is anenvironment variable, consisting of a list of directories. The syntax of PYTHONPATH
is the same as that of the shellvariable PATH.
Here is a typicalPYTHONPATH froma Windows system:
set PYTHONPATH=c:python20lib;
And here is a typicalPYTHONPATH froma UNIX system:
set PYTHONPATH=/usr/local/lib/python
Namespaces and Scoping:
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and
their corresponding objects (values).
A Pythonstatement canaccess variables ina local namespace and inthe global namespace. If a localand a global
variable have the same name, the localvariable shadows the globalvariable.
Eachfunctionhas its ownlocalnamespace. Class methods follow the same scoping rule as ordinary functions.
Pythonmakes educated guesses onwhether variables are localor global. It assumes that any variable assigned
a value ina functionis local.
Therefore, inorder to assigna value to a globalvariable withina function, youmust first use the globalstatement.
The statement global VarName tells Pythonthat VarName is a globalvariable. Pythonstops searching the local
namespace for the variable.
For example, we define a variable Money inthe globalnamespace. Withinthe functionMoney, we assignMoney
a value, therefore Pythonassumes Money as a localvariable. However, we accessed the value of the local
variable Money before setting it, so anUnboundLocalError is the result. Uncommenting the globalstatement
fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The dir( ) Function:
The dir() built-infunctionreturns a sorted list of strings containing the names defined by a module.
The list contains the names of allthe modules, variables and functions that are defined ina module. Following is a
simple example:
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content;
Whenthe above code is executed, it produces the following result:
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the specialstring variable __name__ is the module's name, and __file__ is the filename fromwhichthe
module was loaded.
The globals() and locals() Functions:
The globals() and locals() functions canbe used to returnthe names inthe globaland localnamespaces
depending onthe locationfromwhere they are called.
If locals() is called fromwithina function, it willreturnallthe names that canbe accessed locally fromthat function.
If globals() is called fromwithina function, it willreturnallthe names that canbe accessed globally fromthat
function.
The returntype of boththese functions is dictionary. Therefore, names canbe extracted using the keys()
function.
The reload() Function:
Whenthe module is imported into a script, the code inthe top-levelportionof a module is executed only once.
Therefore, if youwant to reexecute the top-levelcode ina module, youcanuse the reload() function. The
reload() functionimports a previously imported module again. The syntax of the reload() functionis this:
reload(module_name)
Here, module_name is the name of the module youwant to reload and not the string containing the module name.
For example, to reload hello module, do the following:
reload(hello)
Packages in Python:
A package is a hierarchicalfile directory structure that defines a single Pythonapplicationenvironment that
consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available inPhone directory. This file has following line of source code:
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions withthe same name as above:
Phone/Isdn.py file having functionIsdn()
Phone/G3.py file having functionG3()
Now, create one more file __init__.py inPhone directory:
Phone/__init__.py
To make allof your functions available whenyou've imported Phone, youneed to put explicit import statements in
__init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you've added these lines to __init__.py, youhave allof these classes available whenyou've imported the
Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
Whenthe above code is executed, it produces the following result:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
Inthe above example, we have takenexample of a single functions ineachfile, but youcankeep multiple functions
inyour files. Youcanalso define different Pythonclasses inthose files and thenyoucancreate your packages out
of those classes.

More Related Content

What's hot

Python Modules
Python ModulesPython Modules
Python ModulesSoba Arjun
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Pythonprimeteacher32
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAMaulik Borsaniya
 
python Function
python Function python Function
python Function Ronak Rathi
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresIntellipaat
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMINGindupps
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 

What's hot (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
 
Advance python
Advance pythonAdvance python
Advance python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Biopython
BiopythonBiopython
Biopython
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
python Function
python Function python Function
python Function
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
 
Day3
Day3Day3
Day3
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Day2
Day2Day2
Day2
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Python functions
Python functionsPython functions
Python functions
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMING
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 

Similar to Python modules

Similar to Python modules (20)

Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
 
Python modules
Python modulesPython modules
Python modules
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
 
Python modules
Python   modulesPython   modules
Python modules
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
packages.pptx
packages.pptxpackages.pptx
packages.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Python Programming - Functions and Modules
Python Programming - Functions and ModulesPython Programming - Functions and Modules
Python Programming - Functions and Modules
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Chapter - 4.pptx
Chapter - 4.pptxChapter - 4.pptx
Chapter - 4.pptx
 

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
 
Python overview
Python overviewPython overview
Python overview
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python networking
Python networkingPython networking
Python networking
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Python loops
Python loopsPython loops
Python loops
 

Recently uploaded

UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 

Recently uploaded (20)

9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 

Python modules

  • 1. http://www.tutorialspoint.com/python/python_modules.htm Copyright © tutorialspoint.com PYTHON MODULES A module allows youto logically organize your Pythoncode. Grouping related code into a module makes the code easier to understand and use. A module is a Pythonobject witharbitrarily named attributes that youcanbind and reference. Simply, a module is a file consisting of Pythoncode. A module candefine functions, classes and variables. A module canalso include runnable code. Example: The Pythoncode for a module named aname normally resides ina file named aname.py. Here's anexample of a simple module, support.py def print_func( par ): print "Hello : ", par return The import Statement: Youcanuse any Pythonsource file as a module by executing animport statement insome other Pythonsource file. The import has the following syntax: import module1[, module2[,... moduleN] Whenthe interpreter encounters animport statement, it imports the module if the module is present inthe search path. A searchpathis a list of directories that the interpreter searches before importing a module. For example, to import the module hello.py, youneed to put the following command at the top of the script: #!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support.print_func("Zara") Whenthe above code is executed, it produces the following result: Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module executionfromhappening over and over againif multiple imports occur. The from...import Statement Python's from statement lets youimport specific attributes froma module into the current namespace. The from...import has the following syntax: from modname import name1[, name2[, ... nameN]] For example, to import the functionfibonaccifromthe module fib, use the following statement: from fib import fibonacci This statement does not import the entire module fib into the current namespace; it just introduces the item fibonaccifromthe module fib into the globalsymboltable of the importing module. The from...import * Statement:
  • 2. It is also possible to import allnames froma module into the current namespace by using the following import statement: from modname import * This provides aneasy way to import allthe items froma module into the current namespace; however, this statement should be used sparingly. Locating Modules: Whenyouimport a module, the Pythoninterpreter searches for the module inthe following sequences: The current directory. If the module isn't found, Pythonthensearches eachdirectory inthe shellvariable PYTHONPATH. If allelse fails, Pythonchecks the default path. OnUNIX, this default pathis normally /usr/local/lib/python/. The module searchpathis stored inthe systemmodule sys as the sys.path variable. The sys.pathvariable contains the current directory, PYTHONPATH, and the installation-dependent default. The PYTHONPATH Variable: The PYTHONPATH is anenvironment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shellvariable PATH. Here is a typicalPYTHONPATH froma Windows system: set PYTHONPATH=c:python20lib; And here is a typicalPYTHONPATH froma UNIX system: set PYTHONPATH=/usr/local/lib/python Namespaces and Scoping: Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Pythonstatement canaccess variables ina local namespace and inthe global namespace. If a localand a global variable have the same name, the localvariable shadows the globalvariable. Eachfunctionhas its ownlocalnamespace. Class methods follow the same scoping rule as ordinary functions. Pythonmakes educated guesses onwhether variables are localor global. It assumes that any variable assigned a value ina functionis local. Therefore, inorder to assigna value to a globalvariable withina function, youmust first use the globalstatement. The statement global VarName tells Pythonthat VarName is a globalvariable. Pythonstops searching the local namespace for the variable. For example, we define a variable Money inthe globalnamespace. Withinthe functionMoney, we assignMoney a value, therefore Pythonassumes Money as a localvariable. However, we accessed the value of the local variable Money before setting it, so anUnboundLocalError is the result. Uncommenting the globalstatement fixes the problem. #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money
  • 3. Money = Money + 1 print Money AddMoney() print Money The dir( ) Function: The dir() built-infunctionreturns a sorted list of strings containing the names defined by a module. The list contains the names of allthe modules, variables and functions that are defined ina module. Following is a simple example: #!/usr/bin/python # Import built-in module math import math content = dir(math) print content; Whenthe above code is executed, it produces the following result: ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Here, the specialstring variable __name__ is the module's name, and __file__ is the filename fromwhichthe module was loaded. The globals() and locals() Functions: The globals() and locals() functions canbe used to returnthe names inthe globaland localnamespaces depending onthe locationfromwhere they are called. If locals() is called fromwithina function, it willreturnallthe names that canbe accessed locally fromthat function. If globals() is called fromwithina function, it willreturnallthe names that canbe accessed globally fromthat function. The returntype of boththese functions is dictionary. Therefore, names canbe extracted using the keys() function. The reload() Function: Whenthe module is imported into a script, the code inthe top-levelportionof a module is executed only once. Therefore, if youwant to reexecute the top-levelcode ina module, youcanuse the reload() function. The reload() functionimports a previously imported module again. The syntax of the reload() functionis this: reload(module_name) Here, module_name is the name of the module youwant to reload and not the string containing the module name. For example, to reload hello module, do the following: reload(hello) Packages in Python: A package is a hierarchicalfile directory structure that defines a single Pythonapplicationenvironment that consists of modules and subpackages and sub-subpackages, and so on.
  • 4. Consider a file Pots.py available inPhone directory. This file has following line of source code: #!/usr/bin/python def Pots(): print "I'm Pots Phone" Similar way, we have another two files having different functions withthe same name as above: Phone/Isdn.py file having functionIsdn() Phone/G3.py file having functionG3() Now, create one more file __init__.py inPhone directory: Phone/__init__.py To make allof your functions available whenyou've imported Phone, youneed to put explicit import statements in __init__.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 After you've added these lines to __init__.py, youhave allof these classes available whenyou've imported the Phone package. #!/usr/bin/python # Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3() Whenthe above code is executed, it produces the following result: I'm Pots Phone I'm 3G Phone I'm ISDN Phone Inthe above example, we have takenexample of a single functions ineachfile, but youcankeep multiple functions inyour files. Youcanalso define different Pythonclasses inthose files and thenyoucancreate your packages out of those classes.