- LPU MCA Semester 1
- CAB106
- Unit 4
CAB106 · Unit 4: Abstraction, modules and packages
Modules, import statements and packages
11 practice questions
Key points
- A module is a .py file; a package is a folder with __init__.py
- ModuleNotFoundError for a missing module, ImportError for a missing name
- Imports are cached in sys.modules
- The __main__ guard runs code only on direct execution
A module is a single .py file whose names can be reused with import. A package is a folder of modules, marked by an __init__.py file. Common forms are import math (use math.floor), from math import sqrt (use sqrt directly), import math as m and from math import sqrt as r. A star import such as from math import * copies every public name and can overwrite your own names, so it is discouraged.
| Situation | Result |
|---|---|
| Module not found | ModuleNotFoundError |
| Name missing from an existing module | ImportError |
| Same module imported twice | Cached in sys.modules, one object |
Inside a package a sibling module is imported with a relative import such as from . import b; one dot means the current package and two dots mean the parent. Every module has a __name__. When a file is run directly __name__ is "__main__", so the guard if __name__ == "__main__": runs code only for direct execution, not on import. importlib.import_module("name") imports by string, and os.path.basename is an example of a function in a submodule.
Exam trap: importing a module twice does not run it twice. Python caches it in sys.modules.
Try two questions
Which file marks a folder as a regular Python package?
- __main__.py
- __init__.py
- setup.py
- package.py
Show the answer
B. A folder containing __init__.py is treated as a regular package.
Why not A: __main__.py makes a package runnable but does not mark it as a package.
Why not C: setup.py is used for installing, not for marking a package.
Why not D: Python has no special file called package.py.
Inside a package, module a wants to import module b from the same package. Which relative import is correct?
- import .b
- from .. import b
- from . import b
- from b import .
Show the answer
C. One dot means the current package, so from . import b imports its sibling module.
Why not A: The dot form cannot follow a plain import statement.
Why not B: Two dots refer to the parent package, not the current one.
Why not D: That is not valid import syntax.