Is there any effect of unused imports in a Python script?
Asked
Active
Viewed 8,403 times
2 Answers
35
You pollute your namespace with names that could interfere with your variables and occupy some memory.
Also you will have a longer startup time as the program has to load the module.
In any case, I would not become too neurotic with this, as if you are writing code you could end up writing and deleting import os
continuously as your code is modified. Some IDE's as PyCharm detect unused imports so you can rely on them after your code is finished or nearly completed.
-
2So, the program will take more time as compare to w/o those unnecessary imports. right ? – Aashish P Dec 26 '12 at 09:48
-
Startup time delay can be visualized by making a bunch of files with `print "Hello", __name__` and then importing them. Everything imported must be parsed at least once and than the pyc/cache version is interpreted atleast once per run cycle. That can get a bit out of hand, especially if one imported file imports other files which import even more files. – David Oct 01 '13 at 21:04
12
"Unused" might be a bit harder to define than you think, for example this code in test.py:
import sys
import unused_stuff
sys.exit(0)
unused_stuff seems to be unused, but if it were to contain:
import __main__
def f(x): print "Oh no you don't"
__main__.sys.exit = f
Then running test.py doesn't do what you'd expect from a casual glance.

Flexo
- 87,323
- 22
- 191
- 272
-
5hope nobody is writing libraries with such a code. This import would be dangerous even if the OP planned to **use** that module. – joaquin Dec 26 '12 at 10:00
-
4@joaquin True, this is an extreme example, but that doesn't mean there aren't modules that when loaded have more subtle side effects. It was meant as a trivial illustration of a side effect :) – Flexo Dec 26 '12 at 10:02
-
9There are two modules that I have in my personal library whose sole API is the import, that is, all you do is import them nothing to call. The first is nice.py, which runs the program at a lower process priority, the other is timing.py, which installs an atexit handler to report the elapsed time and timestamp when the running program ends. Both of these would look like they are unused, but in fact, they just have a super-minimalist API. – PaulMcG Dec 26 '12 at 10:19