Google Colab: Reload imported modules
Asked Answered
B

3

13

I have a file readfunctions.py inside a folder called functions (in this folder there is also a "init.py" file). In the file readfunctions.py I have defined a function called "read_from_shower".

./functions
    readfunctions.py
    __init__.py

So, I have imported this in my Google Colab Session (from GitHub after I cloned the repository):

from functions.readfunctions import read_from_shower

And it works fine. But then, I have made some changes in my function "read_from_shower" but I can't reload it in Colab.

How can I do it?

Batholomew answered 14/5, 2018 at 21:52 Comment(1)
Take a look at autoreload in IPython Link.Cyclopentane
T
16

You can restart the runtime (which is annoying), or use something like

import importlib
importlib.reload(functions.readfunctions)
Token answered 30/4, 2019 at 9:22 Comment(0)
S
6

Just put this someplace

%load_ext autoreload
%autoreload 2
Sezen answered 4/2, 2021 at 21:16 Comment(1)
Didn't work for me. Lots of autoreload of <package name> failed.Vesture
C
-1

As Daniel also mentioned, this workflow is implemented in IPython Module. You can use it like this (+):

IPython extension to reload modules before executing user code. autoreload reloads modules automatically before entering the execution of code typed at the IPython prompt. This makes for example the following workflow possible:

%load_ext autoreload
%autoreload 2

from foo import some_function

some_function()
Out[4]: 42

# open foo.py in an editor and change some_function to return 43

some_function()
Out[6]: 43

If you encounter problems, you can also use other autoreload options.

  • %autoreload 0: Disable automatic reloading.

  • %autoreload 1: Reload all modules imported with %aimport every time before executing the Python code typed.

  • %autoreload 2: Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.

Note that these are the options I consider as most important. For more info, see here.

You have to run the command before importing the module you want to reload.

Cyclopentane answered 21/1, 2023 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.