In Python, what happens when you import inside of a function?

StackOverflow

What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory?

Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?

Answer rating: 185

Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn"t actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3

As for the benefits: it depends, I guess. If you may only run a function very rarely and don"t need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don"t want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there"s always from my_module import my_function as f for those cases.)

In general practice, it"s probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.





Get Solution for free from DataCamp guru