Why imports can be slow
Import statements execute module code on import. If this is just class/function definitions it is usually very fast; some packages/modules run expensive code on startup. Here is a short example:
my_module1.py
:
def func1():
print("ran func1")
my_module2.py
:
import time
def import_func():
print("running some import-time code...")
time.sleep(1)
print("import startup complete")
# expensive code that executes on import
import_func()
def func2():
print("ran func2")
Working with slow imports
Slow imports can be cumbersome if you run them often, such as rerunning a script frequently to update with changes (the reason the question was origially asked). Thankfully, ipython
now has autoreload that detects code changes and reloads them automatically the next time they are called. This can be manually configured if it doesn't work out of the box. In the example above, autoreload would have behavior like the following:
import my_module1
my_module1.func1()
# prints: "ran func1"
# update func1 on-file as follows:
# def func1():
# print("ran modified func1")
my_module1.func1()
# prints: "ran modified func1" if autoreload is correctly configured.