Let's see what the bytecode will look like for the following two functions:
def func1(): """ test imported each time function is run """ from task import test test() def func2(): """ test was imported at top of module """ test()
As you can see below, func2() saves a lot of steps using the globally imported test function.
>>> dis.dis(func1) 3 0 LOAD_CONST 1 (-1) 3 LOAD_CONST 2 (('test',)) 6 IMPORT_NAME 0 (task) 9 IMPORT_FROM 1 (test) 12 STORE_FAST 0 (test) 15 POP_TOP 4 16 LOAD_FAST 0 (test) 19 CALL_FUNCTION 0 22 POP_TOP 23 LOAD_CONST 3 (None) 26 RETURN_VALUE >>> dis.dis(func2) 3 0 LOAD_GLOBAL 0 (test) 3 CALL_FUNCTION 0 6 POP_TOP 7 LOAD_CONST 1 (None) 10 RETURN_VALUE
Given this in the front, it is probably premature optimization, as pointed out in the delnan comments.
For test located in the global namespace, this is unlikely to cause problems with search performance. The best known way, I think you could see it, if there was a hash clash for test and another name that you use very often, which caused a search for a second name that takes longer. Again, premature optimization to consider this rare case ahead.
source share