Unit 12Modules and Packages
Follows IGNOU MCS-201, Unit 12
As programs grow, keeping all the code in one file becomes unmanageable. Python solves this with modules (single files of reusable code) and packages (folders of modules). This unit shows how to create and import your own modules, how Python finds them, how a file can work both as a script and as a module, how to build packages, and how to use some of the most useful modules of the standard library: os, sys, math, random and statistics.
In this unit you will learn to
- Create a module and import it with
import,from … importandfrom … import *. - Explain how Python searches for modules and add a folder to the search path.
- Distinguish a module from a script and use
if __name__ == "__main__":. - Create a package with
__init__.py, import from it, and controlimport *with__all__. - Use module attributes such as
__name__,__file__and__doc__, and the functionshelp()anddir(). - Use common functions of the
os,sys,math,randomandstatisticsmodules.
Sections in this unit
- 12.1Creating and Using ModulesWhat a Python module is, how to create one, the three ways of importing it, and what happens when a module is imported.10 min
- 12.2The Module Search PathHow Python finds a module using sys.path, what goes into the search path, the ModuleNotFoundError, and three ways to make your own module importable.9 min
- 12.3Modules versus ScriptsThe difference between running a file as a script and importing it as a module, and how __name__ and the main guard let one file serve both purposes.8 min
- 12.4Creating and Importing PackagesOrganising modules into packages: package folders and __init__.py, importing package modules, controlling import * with __all__, and sub-packages.9 min
- 12.5Standard Library Modules: Attributes, os and sysPython's standard library, the attributes every module has (__name__, __file__, __doc__), help() and dir(), and key functions of the os and sys modules.9 min
- 12.6Standard Library Modules: math, random and statisticsCommon functions of the math, random and statistics modules, with worked examples of calculations, random choices and data summaries.11 min