Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do unused imports in Python hamper performance?

Is there any effect of unused imports in a Python script?

like image 617
Aashish P Avatar asked Dec 26 '12 09:12

Aashish P


People also ask

Do unused imports affect performance?

Unused imports have no performance impact at runtime.

Do imports slow down Python?

Startup and Module Importing Overhead. Starting a Python interpreter and importing Python modules is relatively slow if you care about milliseconds. If you need to start hundreds or thousands of Python processes as part of a workload, this overhead will amount to several seconds of overhead.

What happens when a Python file is imported?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.

Should imports be at the top of file Python?

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.


2 Answers

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.

like image 67
joaquin Avatar answered Oct 05 '22 19:10

joaquin


"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.

like image 40
Flexo Avatar answered Oct 05 '22 19:10

Flexo