Skip to content
Advertisement

Performance impact in having a single import per line

does anybody know if there is a performance difference between having all imports from one module in a single line vs one per line. For example, having:

from a import A, B, C, D, E, F, G

instead of:

from a import A
from a import B
from a import C
from a import D
from a import E
from a import F
from a import G

I’m trying to convince my team to use reorder-python-imports in our pre-commit hooks and this doubt is the only obstacle that prevents me from adding it.

Advertisement

Answer

Combining imports is technically faster but there should not be a noticeable performance difference in real world usage. Python modules execute only once, on their first time being imported. After being initialized, you only incur the negligible cost of the additional import statements themselves.

As long as you only do top-level imports, your imports will only ever execute during startup anyway. By combining them you might at best manage to shave off a negligible amount of milliseconds during startup. Read the Python docs on the import mechanism.

Here is my machine’s performance after a million repetitions each:

test1.py

from timeit import timeit

print(timeit("""
from socket import socket
from socket import create_connection
from socket import has_dualstack_ipv6
from socket import getaddrinfo
from socket import gethostbyaddr
"""))
# Prints 2.8450163

test2.py

from timeit import timeit

print(timeit("""
from socket import socket, create_connection, has_dualstack_ipv6, getaddrinfo, gethostbyaddr
"""))
# Prints 0.6992155
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement