Unlike Java, Python modules aren't imported multiple times. Just running import two times will not reload the module. In this scenario, we could create two files; one for Speaker class and another for other classes. In Speaker class we could load the module at the top. But for simplicity of explaining the inheritance which is the core subject of the tutorial, I have merged them in a single file. But this operation will not effect the performance or reload the pyttsx3 as I mentioned earlier. Thank you for pointing out a nice feature of Python.
While I was referring to best practices in programming (and remember, Python's style guide explicitly states where imports should go), with the view that best practice is absolutely something we should follow while teaching newcomers, the claim of performance being identical is demonstrably false.
importtimeitimportstring# warmup this to avoid any potential bias
deffunc_a():importstringforxinrange(10000):x+=1# dummy operation so the loop does something we can compare against
deffunc_b():importstringf=lambdax:x+1forxinrange(10000):f(x)deffunc_c():forxinrange(10000):importstring# Measurements on my laptop, an ageing i7-4500u, but trends should be reproducible
timeit.timeit('func_a()',globals=globals(),number=100)# Gives ~= 0.068
timeit.timeit('func_b()',globals=globals(),number=100)# Gives ~= 0.126
timeit.timeit('func_c()',globals=globals(),number=100)# Gives ~= 0.368
So, point of fact, import is actually a pretty expensive operation; it's 6 times more expensive than simple bytecode ops, and three times more expensive than a function call.
Unlike Java, Python modules aren't imported multiple times. Just running import two times will not reload the module. In this scenario, we could create two files; one for
Speaker
class and another for other classes. InSpeaker
class we could load the module at the top. But for simplicity of explaining theinheritance
which is the core subject of the tutorial, I have merged them in a single file. But this operation will not effect the performance or reload thepyttsx3
as I mentioned earlier. Thank you for pointing out a nice feature of Python.While I was referring to best practices in programming (and remember, Python's style guide explicitly states where imports should go), with the view that best practice is absolutely something we should follow while teaching newcomers, the claim of performance being identical is demonstrably false.
So, point of fact, import is actually a pretty expensive operation; it's 6 times more expensive than simple bytecode ops, and three times more expensive than a function call.
Updated the post to follow the best practices. Thank you a lot for pointing out those. Really appreciate your explanation and effort.