Chapter 4 Functions
4.6 Modules¶
First, it has been discussed before that an imported module can be accessed by an identifier that bares the same name of the module (i.e. math). In addition, constants and functions defined in a module can be accessed by using the module name and the dot (.) operator (i.e. math.e). The former functionality is achieved by registering the name of the module in the binding table. To achieve the latter functionality, an imported module is associated with a binding table of its own, which contains the names of constants and functions defined in the module. For example, the memory structure after the following three lines of code are executed is shown in Fig. 4.2.
![Fig. 4.2 Module name and binding table](../_images/fig4-2.jpeg)
Fig. 4.2 Module name and binding table¶
There are three identifiers in the main binding table: x, y and math. While x and y are put into the binding table by the corresponding assignment statements, math is inserted by the import statement. x and y are associated with the objects 1 and ‘abc’, respectively. math, in contrast, is associated with a binding table, which contains the constants and functions defined in the math module. In the figure, the name sqrt is associated with a function object.
The dot (.) operator syntactically connects a module name identifier to a second identifier (e.g. math.e). The <module>.<identifier> expression is evaluated to the value of identifier, looked up in the binding table of module. For example, when the expression math.e is evaluated, Python first looks for the name math in the main binding table. If it is found, Python follows the corresponding link to find the binding table of math, in which is searches for the identifier e. In each of the two look-ups, if the corresponding identifier is not found, an error will occur.
>>> import math
>>> math.e
2.718281828459045
>>> math.e1
Traceback (most recent call last):
File"<stdin >", line 1, in <module >
AttributeError: 'module' object has no attribute 'e1' >>> math1.e
Traceback (most recent call last):
File "<stdin >", line 1, in <module > NameError: name 'math1 ' is not defined
In the example above, the second command (math.e) successfully returns the value of math.e, since math has been imported to the current binding table and e is a part of the math binding table. However, the third command (math.e1) raises an error because the name e1 is not in the math binding table, and the fourth command (math1.e) raises an error because the name math1 is not in the current binding table. In Python, the dot (.) operator indicates a binding table, specified by the left operand. An identifier is looked up in the specified binding table if it is the right operand of a dot operator (e.g. math.e), but in the current binding table otherwise (e.g. e). The main binding table of IDLE or a Python program is also called the global binding table.
© Copyright 2024 GS Ng.