Performance of using import

Yesterday I discovered, that each import function does not re-import the same function (see my test function ‘test_import.py’. However, if a function has been imported by the from-import function, then each import will always be imported even if it was been done before (see my two other test functions ‘test_3’ and ‘test_4’).

My question is how to avoid unnecessary importing concerning the performance.

The code ‘test_import.py’ contains:

import timeit

import os

def test_1():
  import os
  _ = os.environ['SYSTEMDRIVE']

def test_2():
  _ = os.environ['SYSTEMDRIVE']

import test_3
import test_4

start = timeit.default_timer()
print('Test one')
for wrk in range(1000):
  test_1()
stop = timeit.default_timer()
print('Time: ', stop - start)

start = timeit.default_timer()
print('Test two')
for wrk in range(1000):
  test_2()
stop = timeit.default_timer()
print('Time: ', stop - start)

start = timeit.default_timer()
print('Test three')
for wrk in range(1000):
  test_3.test_3()
stop = timeit.default_timer()
print('Time: ', stop - start)

start = timeit.default_timer()
print('Test four')
for wrk in range(1000):
  test_4.test_4()
stop = timeit.default_timer()
print('Time: ', stop - start)

The code ‘test_3.py’ contains:

def test_3():
  import sys
  _ = sys._getframe().f_code.co_name

The code ‘test_4.py’ contains:

def test_4():
  import sys
  _ = sys._getframe().f_code.co_name

Hopefully those codes will give you the clear problem concerning the performance.

Each modules is only even imported once.
When tou use the from module import name form
The only thing that is repeated is to bind name that is cheap for each module use use that in.

from foo import fred
# is the same effect as
Import foo
fred = foo.fred
del foo
1 Like