Wednesday, June 8, 2022

Dot nomenclature and type of imports

When a module is imported, after the local and global checks within the current program, the imported module will be examined for the called object as well (prior to checking the built-ins). The problem with this is that, unless the called object is explicitly identified with the dot nomenclature, an error will still be generated.

In the following screenshot, we see how the dot nomenclature works:


In this case, we attempt to calculate the square root of a number. Since this operation is unknown to the default Python interpreter, an error is generated. However, if we import the math library in line 2, and then attempt to perform the calculation again, we get an answer.

Note that we explicitly told Python that the square root function is to be found in the math library by using the math.sqrt() command. This is the dot nomenclature that we talked about earlier; the dot indicates

that the sqrt() function can be found in the math library. We will see many other examples of this as we discuss programming further, so while it may not make sense right now, hopefully more examples will help.

In the previous screenshot, we performed a basic module import. This just means that we imported the module, and then referenced something within it through the dot nomenclature. With this type of import, the main program and the imported module maintain their separate namespaces, hence the need to explicitly identify a function through the dot nomenclature.

There are other ways to import modules. One of the most common is to use the from version of import to get only specified objects from a module, rather than the entire module, as shown in the following screenshot.


In this case, we are importing just randint() from the random library in line 4. Because we have explicitly imported this function, it is now part of the overall program's namespace, rather than being separated into the random namespace and requiring the dot nomenclature to call it. This allows us to call it in line 5 without any special conditions.

If we try to do the same for randrange() in line 6, we get an error because we never imported randrange() explicitly. Even if we try to use the dot nomenclature in line 7, we still get an error because the entire random library was not imported.

One way around this is to use the from <module> import * command, which imports nearly all objects from the specified module. The problem with this is the possibility of name shadowing because of all the imported objects, especially if multiple modules are imported this way.

In general, if only a handful of objects are needed, explicitly importing them is the safest way to work with them. If you need most or all of a library, you can use the import * command (it's easier to work with but not as safe) or the dot nomenclature (which is safer but requires more typing).


Share:

0 comments:

Post a Comment