Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

7.2 Importing names

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))

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.