Imports within functions in Python

2

I've seen cases where the developer does the import of a module within a function, some cases mainly in the documentation of Django, why it was not very clear to me, if anyone can help me thank you.

    
asked by anonymous 11.07.2018 / 01:43

1 answer

2

There are 2 reasons why the developer should do this:

  • Performance - The import will only happen when the function is called, and if it is never called, the interpreter will not need to load the module.

  • Retrocompatibility - Imported libraries may only be needed in specific environments (eg Windows vs Linux, Python 2 vs Python 3). The system can call the specified function for each environment and load the compatible libraries into it.

  • 11.07.2018 / 02:32