Question

I'm just wondering, I often have really long python files and imports tend to stack quite quickly.

PEP8 says that the imports should always be written at the beginning of the file.


Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called?

Does it make sense to worry about this? Is there no reason to import libraries within the functions or classes that need them?

Was it helpful?

Solution

Every time Python hits an import statement, it checks to see if that module has already been imported, and if not, imports it. So the imports at the top of your file will happen as soon as your file is run or imported by another module.

There is some overhead to this, so it's generally best to keep imports at the top of your file so that cost gets taken care of up front.

OTHER TIPS

The best place for imports is at the top of your file. That documents the dependencies in one place and makes errors from their absence appear earlier. The import itself actually occurs at the time of the import statement, but this seldom matters much.

It is not typical that you have anything to gain by not importing a library until you are in a function or method that needs it. (There is never anything to gain by doing so inside the body of a class.) It is rare that you want optional dependencies and even rarer that this is the right technique to get them, though. Perhaps you can share a compelling use case?

Does it make sense to worry about this?

No

There no reason to import libraries within the functions or classes that need them. It's just slow because the import statement has to check to see if it's been imported once, and realize that it has been imported.

If you put this in a function that's called frequently, you can waste some time with all the import checking.

Imports happen when the module that contains the imports gets executed or imported, not when the functions are called.

Ordinarily, I wouldn't worry about it. If you are encountering slowdowns, you might profile to see if your problem is related to this. If it is, you can check to see if your module can divided up into smaller modules.

But if all the files are getting used by the same program, you'll just end up importing everything anyway.

If a function inside a module is the only one to import a given other module (say you have a function sending tweets, only if some configuration option is on), then it makes sense to import that specific module in the function.

Unless I see some profiling data proving otherwise, my guess is that the overhead of an import statement in a function is completely negligible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top