How to import anything

So far, we have used two different versions of the import statement:

  • Importing a module and then using the module name to access something defined within that module. For example:
    import math
    print(math.pi)
  • Importing something from a module and then using that thing directly. For example:
    from math import pi
    print(pi)

The import statement is very powerful, however, and we can do all sorts of interesting things with it. In this section, we will look at the different ways in which you can use the import statement to import modules and packages, and their contents, into your program.

What does the import statement actually do?

Whenever you create a global variable or function, the Python interpreter adds the name of that variable ...

Get Modular Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.