Imports within Python functions

Asked

Viewed 112 times

2

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

1 answer

2


There are 2 reasons the developer does this:

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

  2. Backcompatibility - Imported libraries may be required only in specific environments (example Windows vs Linux, Python 2 vs Python 3). The system can call the specific function for each environment and load the supported libraries into it.

  • Thank you Begnini.

  • In fact, there is one more reason that is "avoid circular imports" - that is, the function code in module A needs to access attributes or functions that are in module B that in turn imports (directly or indirectly) module A. Thus, this prevents a reference to incomplete module B from being available during the import of module A - and, during the execution of A functions, since B is already in memory, Imports have only the same impact as a variable association (that is, they do not imply finding and compiling the disk file)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.