I've always asked myself, why is there a way to import a certain function from a module, example: from tkinter import ttk
instead of just importing the whole module, --> import tkinter
does it make the program run faster ?
I've always asked myself, why is there a way to import a certain function from a module, example: from tkinter import ttk
instead of just importing the whole module, --> import tkinter
does it make the program run faster ?
If you use timeit
to test them:
import timeit
print(timeit.Timer('''
from tkinter import ttk
''').timeit())
# 0.47940059999999995
print(timeit.Timer('''
import tkinter
''').timeit())
# 0.09511329999999996
import the full module would be faster than only import specific module.
The memory usage of them(tested by memory_profiler
):
from tkinter import ttk
Line # Mem usage Increment Line Contents
================================================
1 18.719 MiB 18.719 MiB @profile
2 def test():
3 21.297 MiB 2.578 MiB from tkinter import ttk
(>2.6)
And:
import tkinter
Line # Mem usage Increment Line Contents
================================================
1 18.676 MiB 18.676 MiB @profile
2 def test():
3 21.070 MiB 2.395 MiB import tkinter
(<=2.5M)
If you only import specific attribute.It would be faster(a little) than import the full module:
import timeit
print(timeit.Timer('''
math.sqrt(4)
''', setup="import math").timeit())
# 0.10590600000000006
print(timeit.Timer('''
sqrt(4)
''', setup="from math import sqrt").timeit())
# 0.08237790000000011
Use from tkinter import ttk
just for convenience.if we want to use some sub-attribute, we don't need to type the full module name.You could learn more differences on the question.
PS: I think this overhead is not a big problem.
There is no memory or speed difference (the whole module has to be evaluated either way, because the last line could be Y = something_else). It can only matter if you are calling a function a lot of times in a loop (millions or more). Doing the double dictionary lookup will eventually accumulate.
Although import tkinter and from tkinter import ttk both import the entire tkinter module, the latter uses name binding so only ttk is accessible to rest of the code.
For some people this would be the preferred style since it only makes accessible the functions you explicitly stated.
It does however introduce potential name conflicts. Note you can also explicitly import functions and rename them with from tkinter import ttk as tkinter_ttk, a convention that meets the explicit import and is less likely to gave name space collisions.
This doesn't make a practical difference, but it DOES indeed make a difference, however small. this is because in the import x version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using from x import y, you have only one lookup.
look at this Python import X or from X import Y? (performance)