How to Import External Code in Python

Problem Formulation and Solution Overview

This article will show you how to import external Python code and use this code in another Python script.

To make it more interesting, we have the following running scenario:

πŸ‘©β€πŸ« Fun Example: Pam, a High School Teacher, wants an easier way to calculate exam totals and produce student averages. The functions to produce these results are located in an external Python file. She has asked for your help.


To follow along, create a file called calcs.py. Copy and paste the contents shown below into this file. Save and place this file into the current working directory.

Contents of calcs.py:

def ClassAverage(lst):
    return sum(lst) / len(lst)

def IncreaseGrades(lst):
    return [x+2 for x in lst]

def DecreaseGrades(lst):
    return [x-3 for x in lst]

def DecreaseGrades(lst):
    return [x-3 for x in lst]

def FailStudent(sname, el):
    return (f'Sorry {sname[el]} you failed.')

πŸ’¬ Question: How would we write code to import and call these functions from another file?

We can accomplish this task by one of the following options:

  • Method 1: Use from file import function
  • Method 2: Use from file import *
  • Method 3: Use exec()
  • Method 4: Use import file
  • Method 5: Run from a subfolder

Method 1: Use “from file import function”

This example calls in one (1) specific function from the calcs.py file, ClassAverage(). This code does not have access to any other functions from this file.

This code calculates the average grade for the Class.

from calcs import ClassAverage

std_grades = [76, 53, 68, 49, 81]
class_avg = ClassAverage(std_grades)
print(f'The Average Grade for the Class is {class_avg}%.')

The first line in the above code snippet imports the ClassAverage() function from the calcs.py file.

The following line declares a list of student grades. The results save to std_grades.

The next line calls in the ClassAverage() function and passes it one (1) argument, std_grades. The results of this calculation save to class_avg and are output to the terminal.

The Average Grade for the Class is 65.4%.

πŸ’‘Note: To import additional functions, place a comma after the first function as follows: from calcs import Class Average, IncreaseGrades.


Method 2: Use “from file import *”

This example uses import *. This lets Python know that all functions are available to use.

This code increases the students’ grades by two (2) grade points.

from calcs import *

std_grades = [76, 53, 68, 49, 81]
new_grades = IncreaseGrades(std_grades)
print(new_grades)

The first line in the above code snippet imports all functions from the calcs.py file.

The following line declares a list of student grades. The results save to std_grades.

The next line calls the IncreaseGrades() function and passes it one (1) argument, std_grades. The results of this calculation save to new_grades and are output to the terminal.

[78, 55, 70, 51, 83]

Method 3: Use exec() and file.read()

This example uses exec() and with open to read in the contents of the calcs.py file.

This code decreases the students’ grades and re-calculates the average grade.

with open('calcs.py') as fp: exec(fp.read())

std_grades = [76, 53, 68, 49, 81]
new_grades = DecreaseGrades(std_grades)
class_avg = ClassAverage(new_grades)

print(new_grades)
print(class_avg)

The first line in the above code snippet reads in the calcs.py file and saves this as a File Object, fp. If output to the terminal, a File Object similar to below would display.

<_io.TextIOWrapper name='calcs.py' mode='r' encoding='cp1252'>

Then exec() is called and passed one (1) argument, fp.read(), which reads the contents of the file.

The following line declares a list of student grades. The results save to std_grades.

The next line calls the DecreaseGrades() function and passes it one (1) argument, std_grades. The results of this calculation save to new_grades.

Then, the ClassAverage() function is called and passed one (1) argument, new_grades. The results of this calculation save to class_avg.

The contents of the above variables are output to the terminal.

[73, 50, 65, 46, 78]
62.4

Method 4: Use “import file”

This example uses from import. To access the functions from the calcs.py file, you need a direct reference, such as calcs.function().

This code informs the specified student they have failed.

import calcs

std_names = ['Amy', 'Ben', 'Art', 'Joe', 'Zoe']
std_grades = [76, 53, 68, 49, 81]
std_failed = calcs.FailStudent(std_names, 3)
print(std_failed)

The first line in the above code snippet imports all functions from the calcs.py file.

The following two (2) lines declare a list of students and a corresponding list of grades. These results save to std_names and std_grades, respectively.

The next line calls the file name imported earlier (calc) and appends the function FailStudent(). This function is passed two (2) arguments, std_names and the index number of the failing student. The results save to std_failed and are output to the terminal.

Sorry Joe you failed.

Method 5: Run from a sub-folder

This example places the calcs.py file inside the test folder. This file is then referenced in the code.

import os
import sys

subfolder = "test/"
sys.path.append(os.path.abspath(subfolder))

import calcs

std_grades = [76, 53, 68, 49, 81]
new_grades = calcs.DecreaseGrades(std_grades)
class_avg = calcs.ClassAverage(new_grades)
print(class_avg)

The first (2) lines in the above code snippet import the os and the sys libraries used to locate the sub-folder.

The following two (2) lines let the code know to set the location to the subfolder (test). For this example, the calcs.py file resides in this folder.

The following line imports calcs.

To confirm this works, the final four (4) lines declare a list of students’ grades and calculates the Class Average. The results are output to the terminal.

62.4

πŸ’‘Note: The above code is the same code used in Method 3 above.


Summary

This article has provided five (5) ways to import a Python file to select the best fit for your coding requirements.

Good Luck & Happy Coding!