Skip to main content
Engineering LibreTexts

7.2: Importing Names

  • Page ID
    117565
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    Learning Objectives

    By the end of this section you should be able to

    • Import functions from a module using the from keyword.
    • Explain how to avoid a name collision when importing a module.

    The from keyword

    Specific functions in a module can be imported using the from keyword:

        from area import triangle, cylinder

    These functions can be called directly, without referring to the module:

        print(triangle(1, 2))
        print(cylinder(3, 4))
    Exploring further

    As shown below, the from keyword can lead to confusing names.

    Checkpoint: Importing functions
    Concepts in Practice \(\PageIndex{1}\): The from keyword

    Which import statement would be needed before running print(sqrt(25))?

    1. from math import sqrt
    2. import sqrt from math
    3. import math
    Answer

    a. This statement imports the sqrt function defined in the math module.

    Concepts in Practice \(\PageIndex{2}\): The from keyword

    How many variables are defined by the statement from math import sin, cos, tan?

    1. 0
    2. 3
    3. 4
    Answer

    b. A variable is defined for each function imported: sin, cos, and tan.

    Concepts in Practice \(\PageIndex{3}\): The from keyword

    What error would occur if attempting to call a function that was not imported?

    1. ImportError
    2. NameError
    3. SyntaxError
    Answer

    b. A name error occurs when a variable name is not found, which might be due to a missing import statement.

    Name collisions

    Modules written by different programmers might use the same name for a function. A name collision occurs when a function is defined multiple times. If a function is defined more than once, the most recent definition is used:

        from area import cube
    
        def cube(x):    # Name collision (replaces the imported function)
          return x ** 3
        
        print(cube(2)) # Calls the local cube() function, not area.cube()

    A programmer might not realize the cube function is defined twice because no error occurs when running the program. Name collisions are not considered errors and often lead to unexpected behavior.

    Care should be taken to avoid name collisions. Selecting specific functions from a module to import reduces the memory footprint; however, importing a complete module can help to avoid collisions because a module.name format would be used. This is a tradeoff the programmer must consider.

    Checkpoint: Module and function names
    Concepts in Practice \(\PageIndex{4}\): Name collisions

    A program begins with from area import square, circle. What code causes a name collision?

    def area(phone):
      """Gets the area code of a phone number."""
    def circle(x, y, size):
      """Draws a circle centered at (x, y)."""
    
    def is_square(length, width):
      """Returns True if length and width are equal."""
    Answer

    b. This statement replaces the previously imported circle function, even though circle() and area.circle() have different parameters.

    Concepts in Practice \(\PageIndex{5}\): Name collisions

    A program begins with import area. What code causes a name collision?

    1. area = 51
      
    2. import cylinder from volume
      
    3. def cube(size):
        """Generates a "size X size" rubik's cube."""
    Answer

    a. Assigning the area variable replaces the previously imported module with the integer 51 . The variable can no longer be used to call functions in the area module.

    Concepts in Practice \(\PageIndex{6}\): Name collisions

    Which line will cause an error?

    1
    def hello():
    2
    print("Hello!")
    3
     
    4
    def hello(name):
    5
    print("Hello,", name)
    6
     
    7
    hello()
    8
    hello("Chris")
    1. line 4
    2. line 7
    3. line 8
    Answer

    b. The most recent definition of hello() requires one argument, so this line would result in an error.

    Exploring further

    If a name is defined, imported, or assigned multiple times, Python uses the most recent definition. Other languages allow multiple functions to have the same name if the parameters are different. This feature, known as function overloading, is not part of the Python language.

    Try It: Missing imports

    Add the missing import statements to the top of the file. Do not make any changes to the rest of the code. In the end, the program should run without errors.

    Interactive Code
    def is_prime(n):
        """Returns True if n is prime."""
        if n < 2:
            return False
        for i in range(2, int(sqrt(n)) + 1):
            if n % i == 0:
                return False
        return True
    
    # Test the is_prime function
    for n in range(10):
        if is_prime(n):
            print(n, "is prime")
        else:
            print(n, "is NOT prime")
    
    def pizza_rate(size, price):
        """Calculates the value of a pizza coupon.
    
        Args:
            size (int): Diameter of the pizza in inches.
            price (float): Advertised price of the pizza.
    
        Returns:
            float: The pizza's price per square inch.
        """
        return price / circle(size / 2)
    
    # Test the pizza_rate function
    print()
    print("  Small for $4.99:", pizza_rate(10, 4.99))
    print(" Medium for $5.99:", pizza_rate(12, 5.99))
    print("  Large for $7.99:", pizza_rate(14, 7.99))
    print("X-Large for $9.99:", pizza_rate(16, 9.99))
    
     
    Answer (prime_pizza1.py)

    from math import sqrt
    from area import circle

    def is_prime(n):
    """Returns True if n is prime."""
    if n < 2:
    return False
    for i in range(2, int(sqrt(n)) + 1):
    if n % i == 0:
    return False
    return True

    # Test the is_prime function
    for n in range(10):
    if is_prime(n):
    print(n, "is prime")
    else:
    print(n, "is NOT prime")

    def pizza_rate(size, price):
    """Calculates the value of a pizza coupon.

    Args:
    size (int): Diameter of the pizza in inches.
    price (float): Advertised price of the pizza.

    Returns:
    float: The pizza's price per square inch.
    """
    return price / circle(size / 2)

    # Test the pizza_rate function
    print()
    print(" Small for $4.99:", pizza_rate(10, 4.99))
    print(" Medium for $5.99:", pizza_rate(12, 5.99))
    print(" Large for $7.99:", pizza_rate(14, 7.99))
    print("X-Large for $9.99:", pizza_rate(16, 9.99))

    Try It: Party favors

    The following program does not run correctly because of name collisions. Fix the program by modifying import statements, function calls, and variable assignments. The output should be:

        Bouncy ball area: 13
        Bouncy ball volume: 4
        Cone hat area: 227
        Cone hat volume: 209
    Interactive Code
    from area import cone, sphere
    import math
    
    def cone(radius, height):
        """Gets the volume of a cone."""
        return math.pi * radius**2 * height/3
    
    def sphere(radius):
        """Gets the volume of a sphere."""
        return 4/3 * math.pi * radius**3
    
    # A bouncy ball is 2 inches in diameter.
    area = sphere(1)
    volume = sphere(1)
    print("Bouncy ball area:", round(area))
    print("Bouncy ball volume:", round(volume))
    
    # A cone hat is 10 inches in diameter and 8 inches tall.
    area = cone(5, 8)
    volume = cone(5, 8)
    print("Cone hat area:", round(area))
    print("Cone hat volume:", round(volume))
    
     
    Answer (area.py)

    import area
    import math

    def cone(radius, height):
    """Gets the volume of a cone."""
    return math.pi * radius**2 * height/3

    def sphere(radius):
    """Gets the volume of a sphere."""
    return 4/3 * math.pi * radius**3

    # A bouncy ball is 2 inches in diameter.
    ball_area = area.sphere(1)
    ball_volume = sphere(1)
    print("Bouncy ball area:", round(ball_area))
    print("Bouncy ball volume:", round(ball_volume))

    # A cone hat is 10 inches in diameter and 8 inches tall.
    cone_area = area.cone(5, 8)
    cone_volume = cone(5, 8)
    print("Cone hat area:", round(cone_area))
    print("Cone hat volume:", round(cone_volume))


    This page titled 7.2: Importing Names is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.