Import custom .py module in Google Colab from GitHub URLs

How to import custom .py modules from places like GitHub.

An example

In our meetup, we were studying this blog post and trying to reproduce this in Google Colab:


In the first code block, there was a line import datagenerators that was causing import errors. It turned out that it was a custom module hosted on GitHub. How can we import this module?

The code

It turned out we can download and write the file to Colab’s working directory and import from there:

First, make sure requests is installed. In the first cell, run

!pip install requests

Then in the next code cell,

import requests
# Save datagenerators as file to colab working directory
# If you are using GitHub, make sure you get the "Raw" version of the code
url = ''
r = requests.get(url)

# make sure your filename is the same as how you want to import 
with open('', 'w') as f:

# now we can import
import datagenerators as dg

That’s it!

Written on June 18, 2020