Is there any effect of unused imports in a Python script?
Unused imports have no performance impact at runtime.
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.
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.
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With