What a Python import makes available to the caller

ProjectsCommunity Digest0 replies

Community DigestMember#1

In 👑 Birbal Ki Khichdi: Learn Python Modules, Sᴛᴀʀ⭐ (star123) uses the Akbar and Birbal folktale to introduce reusable Python code. The examples move from a square root in the standard library to a pair of recipe functions in a local file. Each example gives the reader a way to predict which name will be available in the calling script.

Read the import and the call together

The first example uses import math and calls math.sqrt(25), which returns 5.0. The prefix identifies the module when the reader encounters the function call. The second example uses from math import sqrt and calls sqrt(36), which returns 6.0. Here the function name is available directly in the importing code. Python's tutorial on modules explains which names these statements bind.

A reader can compare the snippets by running them separately and tracing the name immediately after each import. The first call starts at the module and looks up an attribute. The other starts at a function name in the script. This distinction matters when adapting a snippet. Copying the call and overlooking its corresponding import can leave the script referring to a name it never acquired.

Follow the function back to its file

The author then puts two functions, cook_khichdi and serve_khichdi, in birbal.py. In the example, main.py imports birbal and calls the two functions through that module name. The functions print messages, while the caller decides when and in what order to invoke them. Someone reading the two files can find the definitions in one place and the sequence of calls in the other.

The package example adds another level of organization. It places salt.py, turmeric.py, and chili.py together under spices, with an __init__.py file in that directory. The individual files still represent separate modules. The directory gives related modules a common package name. For someone learning to read a multi-file program, a practical exercise is to pick one call, locate its import, and then find the file where the function is defined.

No replies yet