Modules and Packages

1. Describe a python module.
A module is a file containing Python definitions and statements. A module can define functions, classes, and variables, and it can include runnable code.
2. How to create a Python module?
To create a module, you typically create a Python file with a “.py” extension.
3. Explain __name__ and its use-case.
__name__ is a special built-in variable that is used to differentiate whether a Python script is being run as the main program or if it is being imported as a module into another script.
4. Explain if __name__ == "__main__": use-case.
The script will run when the module is the main program. If it is not the main program, then it will skip the if __name__ == "__main__": block.
5. What does sys.modules returns?
sys.modules provides a dictionary that maps module names to the corresponding module objects. It is essentially a cache of all modules that have been imported.
6. What is sys.modules common use case?
To inspect the modules that have been imported during the current Python session.
7. What does sys.path returns?
sys.path returns the import paths where python will look in order to find files to import.
8. How to add import paths in to sys.path?
export PYTHONPATH = "file_path"
9. What is the process of importing a module from a file?
  1. Python will first check the sys.modules cache to see if the module has already been imported. If so, it will use the reference in there.
  2. Else, it will create a new module object and loads the source code from file and adds the entry to sys.modules
10. Explain the responsibilities of a finder and loader when importing modules.
  • Finder is responsible for finding the modules
  • Loader is responsible to load the source code to compile and execute it.
11. What are packages in python?
A package is a collection of Python modules (and possibly other packages) organised in a directory.
12. Explain the purpose of packages.
A package is a way of organising related modules into a single directory hierarchy.
13. Explain the purpose __init__.py in the package.
The __init__.py file tells python that the directory is a package as opposed to a standard directory.
14. Explain the process of importing the inner package from a nested package.
We must import outer packages that the inner package is dependent on. If not, python will not be able to detect the sub packages.
Last updated on 23 Aug 2024