28👍
You surely must have noticed that almost all Python code does the imports at the top of the file. There’s a reason for that: the overhead of importing is minimal, and the likelihood is that you will be importing the code at some point during the process lifetime anyway, so you may as well get it out of the way.
The only good reason to import at function level is to avoid circular dependencies.
Edit Your comments indicate you haven’t understood how web apps generally work, at least in Python. They don’t start a new process for each request and import the code from scratch. Rather, the server instantiates processes as required, and each one serves many requests until it is finally killed. So again it is likely that during that lifetime, all the imports will end up being needed.
5👍
Import Statement Overhead
From Python Performance Tips:
It’s often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python’s interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.
- [Django]-Celery creating a new connection for each task
- [Django]-Sort order of Django Admin records
- [Django]-Django URLS, how to map root to app?
-1👍
When the script is run, it will store the modules in memory, i’m sure you understand that.
If you’re importing on a local scope, the module will be imported each time the client calls the function. But if the module is imported at a global level, there will be no need for that!
So, in this case: global import wins.
- [Django]-Django Rest Framework – Could not resolve URL for hyperlinked relationship using view name "user-detail"
- [Django]-Django content types – how to get model class of content type to create a instance?
- [Django]-Django, ImportError: cannot import name Celery, possible circular import?