HOW TO IMPORT: A DEEPER LOOK IN PYTHON PROGRAMMING

IMPORT: A DEEPER LOOK

You’ve imported modules (such as math and random) with a statement like:

import module_name

then accessed their features via each module’s name and a dot (.). Also, you’ve imported a specific identifier from a module (such as the decimal module’s Decimal type) with a statement like:

from module_name import identifier

then used that identifier without having to precede it with the module name and a dot (.).

Importing Multiple Identifiers from a Module

Using the from import statement you can import a comma­separated list of identifiers from a module then use them in your code without having to precede them with the module name and a dot (.):

view code image

In [1]: from math import ceil, floor
In [2]: ceil(10.3)
Out[2]: 11
In [3]: floor(10.7)
Out[3]: 10

Trying to use a function that’s not imported causes a NameError, indicating that the name is not defined.

Caution: Avoid Wildcard Imports

You can import all identifiers defined in a module with a wildcard import of the form

from modulename import *

This makes all of the module’s identifiers available for use in your code. Importing a module’s identifiers with a wildcard import can lead to subtle errors—it’s considered a dangerous practice that you should avoid. Consider the following snippets:

In [4]: e = 'hello'
In [5]: from math import *
In [6]: e
Out[6]: 2.718281828459045

Initially, we assign the string 'hello' to a variable named e. After executing snippet [5] though, the variable e is replaced, possibly by accident, with the math module’s constant e, representing the mathematical floating-­point value e.

Binding Names for Modules and Module Identifiers

Sometimes it’s helpful to import a module and use an abbreviation for it to simplify your code. The import statement’s as clause allows you to specify the name used to reference the module’s identifiers. For example, in Section 3.14 we could have imported the statistics module and accessed its mean function as follows:

view code image

In [7]: import statistics as stats
In [8]: grades = [85, 93, 45, 87, 93]
In [9]: stats.mean(grades)
Out[9]: 80.6

As you’ll see in later chapters, import as is frequently used to import Python libraries with convenient abbreviations, like stats for the statistics module. As another example, we’ll use the numpy module which typically is imported with

import numpy as np

Library documentation often mentions popular shorthand names.
Typically, when importing a module, you should use import or import as statements, then access the module through the module name or the abbreviation following the as keyword, respectively. This ensures that you do not accidentally import an identifier that conflicts with one in your code.

*

Post a Comment (0)
Previous Post Next Post