0


Basically, I want to know if importing standard libraries in every module is better/worse than just importing the standard module once in a module and reusing it in other modules. In other words, I wanted to know if there is any speed/performance difference between the following two codes:

"""
One way - Just importing time module only once
"""
# /usr/bin/python
# mytime.py
import time

def get_time():
    return time.time()


# /usr/bin/python
# usingtime.py
import mytime

print (mytime.time() - mytime.time.time())



"""
Another way - importing time module as needed
"""
# /usr/bin/python
# mytime.py
import time

def get_time():
    return time.time()


# /usr/bin/python
# usingtime.py
import time
import mytime

print (mytime.time() - time.time())

Which code is better? or does it really matter?

amulllb
  • 3,036
  • 7
  • 50
  • 87
  • You mean print (mytime.get_time() - time.time()) right? – aneroid Aug 01 '12 at 17:36
  • 2
    possible duplicate of [Does python optimize modules when they are imported multiple times?](http://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times) – jterrace Aug 01 '12 at 17:42

2 Answers2

2

There's no reason to re-import time in the second example, which is effectively what you're doing. For elegance, you should only import a module in the same module that (directly) uses it.

Imagine having imports 3 levels deep (one module imports another module which imports another module...) and keeping track of all those imports in the first, top-level module! It would be a nightmare to maintain.

As far as speed, I believe there will be a negligible performance hit by re-importing. The Python interpreter doesn't do a full re-import when importing more than once.

mach
  • 462
  • 1
  • 7
  • 13
1

From: http://docs.python.org/reference/simple_stmts.html#the-import-statement

The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.

Modules loaded via import are essentially singletons. On the first import of the module, code in module global scope will get executed (initialization of the module) and the module instance is added to sys.modules. The next import in any other module will just refer to this initialized instance. The cost is negligible.

Trivial example:

a.py

print "HELLO"

b.py

import a
import c

c.py

import a

In the interactive interpreter:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import b
HELLO
>>>

(notice how "HELLO" is printed only once)

Jeremy Brown
  • 17,880
  • 4
  • 35
  • 28