Previous Lesson Table of Contents Next Lesson

As you start to write your own code, you may realize that you have a lot of useful code that can be re-used from one project to the next. Perhaps you wrote so much code and want to break it up into individual files. How do we then “combine” them?

This where the concept of an import comes in. Imports allow us to utilize code from multiple files in one file simultaneously. To see how it works, suppose we have a file called library.py that looks like this:

CONSTANT = 5

def f(x):
    return x + 1

Now let’s suppose you want to use these functions and variables elsewhere. You don’t need to copy and paste them. Assuming that library.py is in the right place (don’t worry about this, as the details of importing are a little opaque for our purposes), we can write:

import library

print(library.CONSTANT)
print(library.f(1))

This will output:

5
2

To utilize library.py, we need to write the import keyword followed by the name of the file, which in this case is library. Then, essentially every variable and function that is created is an attribute of the library variable (which refers to library.py) and is accessible for use.

This is not the only way to do an import. Alternatively, you can do:

from library import CONSTANT, f

print(CONSTANT)
print(f(1))

This will also output:

5
2

By using this from...import syntax, we can use the variables and functions directly as we had defined them ourselves instead of library.<name>. One downside though is that we cannot name any other variables with those names (i.e. CONSTANT and f), as we would then overwrite whatever we imported from the original library.py.

The import concept is relatively straightforward, but there are some gnarly details that were deliberately omitted, which surround how Python imports files and where it looks for them. Note that if it can’t find the file to import, it raises an ImportError.

Let’s stop here and answer questions to review what we learned:

  • Suppose you have a file called helpers.py that defines a function increment, which accepts a number and returns its value plus one. Import the file (using the non-from syntax) and call the function with an input of 2. (solution).

  • Use the from syntax instead to import the increment function and pass it an input of 3 instead. (solution).

With imports explained, we will now move on to the concept of inheritance.