4.14 import: A Deeper Look

Importing Multiple Identifiers from a Module

  • Use from…import to import a comma-separated list of identifiers from a module then use them without having to precede them with the module name and a dot (.):
In [1]:
from math import ceil, floor
In [2]:
ceil(10.3)
Out[2]:
11
In [3]:
floor(10.7)
Out[3]:
10

Caution: Avoid Wildcard Imports

  • Import all identifiers defined in a module with a wildcard import.
  • Makes all of the module’s identifiers available.
  • Can lead to subtle errors.
  • Considered a dangerous practice.
In [4]:
e = 'hello'
In [5]:
from math import *
In [6]:
e
Out[6]:
2.718281828459045
  • After executing the import, variable e is replaced, possibly by accident, with the math module’s constant 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.
In [7]:
import statistics as stats
In [8]:
grades = [85, 93, 45, 87, 93]
In [9]:
stats.mean(grades)
Out[9]:
80.6

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 4 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.