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.
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.