DEV Community

Discussion on: Inheritance in Python

Collapse
 
arsho profile image
Ahmedur Rahman Shovon

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.

Collapse
 
habilain profile image
David Griffin • Edited

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.

import timeit
import string # warmup this to avoid any potential bias

def func_a():
  import string
  for x in range(10000):
      x += 1  # dummy operation so the loop does something we can compare against

def func_b():
  import string
  f = lambda x: x + 1
  for x in range(10000):
      f(x)

def func_c():
  for x in range(10000):
    import string

# 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
Enter fullscreen mode Exit fullscreen mode

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.

Thread Thread
 
arsho profile image
Ahmedur Rahman Shovon

Updated the post to follow the best practices. Thank you a lot for pointing out those. Really appreciate your explanation and effort.