Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Importing at function level VS. Module level

When in doubt, I typically place my import statements at the top of the module. Often, this cuts down on repetition, which is nice. Is there a performance downside, though, in the case where only a single function (or class) requires the import?

does the following only import when the function is called?

     def func():
         from task import test

If so, I imagine that might be a slight efficiency. I also assume that you could get some added points for faster garbage collection and variable scoping, since the imported objects would not be added to the global dictionary. As another poster nicely put it:

This is mostly due to variable look-up. Looking up a variable in the global scope requires a dictionary look-up. In contrast, the compiler determines local names statically and references them by index, so no dictionary look up is required.

Are those fair assumptions are am I totally off base?

Thanks

like image 899
Ben Avatar asked Jan 27 '12 17:01

Ben


1 Answers

An import in a function is only imported when the function runs. Keep in mind that in Python, all statements are executed when they are encountered, and imports are statements like anything else. Top-level imports are imported when the module is imported, because they are top-level statements in the module.

Your concerns about name lookup are misguided: the difference is negligible, and should only be considered if profiling shows a problem.

I only import modules into function scope for two reasons: 1) to fix circular import problems, which btw likely could be solved in other ways by refactoring, or 2) if the module is optional, and the function isn't used by many of my users. In the case of 2), the module can be entirely missing, and there won't be a problem unless someone invokes the function.

like image 93
Ned Batchelder Avatar answered Oct 06 '22 17:10

Ned Batchelder