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?
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?
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.
Professional-quality code does more than just run without bugs. It’s clean, readable, and easy to maintain. To step up from a capable Python coder to a professional developer, you need to learn indu...
The genesis of this book began in 2012. Hadoop was being explored in mainstream organizations, and we believed that information architecture was about to be transformed. For many years, business intel...
Deep Learning for Coders with fastai and PyTorch: AI Applications Without a PhD. Deep learning is often seen as the exclusive domain of math PhDs and big tech companies. But as this how-to guide sh...
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems PDF, 2nd Edition. This book assumes you know next to nothing about m...