Python Language: Modules: The FOSSEE Group
Python Language: Modules: The FOSSEE Group
Mumbai, India
Outline
1 Python modules
Modules
Modules
Modules . . .
Test
1_script.py
script_1.py
one11.py
_one11.py
one script.py
one,script;xxx.py
one.two.py
Modules: example
Modules: example
Python path
In IPython type the following
import sys
sys.path
Running a module
$ python fib.py
1 1 2 3 5 8
fib(10)
# EOF
FOSSEE Team (IIT Bombay) Modules 12 / 19
Python modules
Modules: example
Using __name__
import fib
The import is successful
But fib(10), gets run
Add it to the following if block
if __name__ == "__main__":
fib(10)
Now the script runs properly
As well as the import works; the code is not
executed
__name__ is local to every module and is equal to
’__main__’ only when the file is run as a script.
FOSSEE Team (IIT Bombay) Modules 14 / 19
Python modules
Using __name__
import fib
The import is successful
But fib(10), gets run
Add it to the following if block
if __name__ == "__main__":
fib(10)
Now the script runs properly
As well as the import works; the code is not
executed
__name__ is local to every module and is equal to
’__main__’ only when the file is run as a script.
FOSSEE Team (IIT Bombay) Modules 14 / 19
Python modules
print(__name__)
if __name__ == ’__main__’:
fib(10)
# EOF
FOSSEE Team (IIT Bombay) Modules 15 / 19
Python modules
Stand-alone scripts
Standard library
Operating system interface: os, os.path
System, Command line arguments: sys
Regular expressions: re
Math: math, random
Internet access: urllib, smtplib
Data compression: zlib, gzip, bz2, zipfile,
and tarfile
Unit testing: doctest and unittest
And a whole lot more!
Check out the Python Library reference:
http://docs.python.org/lib/lib.html
FOSSEE Team (IIT Bombay) Modules 18 / 19
Python modules
Summary
Creating modules
Importing modules
Running modules as scripts
__name__