0

With respect to least runtime on web app, what is the ideal place to keep my imports in views.py

Say I want to validate and process some form entries with external modules. My current code:

from django.shortcuts import render

from .forms import *

import re
import module1
import module2

def index(request):
    form = MyForm()
    if request.method == 'POST':
        form = MyForm(request.POST)

        if form.is_valid():
            #
            #Process my stuff here using re, module1, module2
            #

return render(request, 'index.html', context)

But what good is it doing by importing module re, module1, module 2 before hand if condition if form.is_valid(): failed? Or condition if request.method == 'POST': fails? That is when the form was never submitted.

Would importing these modules after these conditions are passed (because thats when they are actually needed) cause any less runtime overhead on program or webapp when these conditions fail? avoiding unnecessary imports when they are not needed?

Psuedo code of my idea:

if form.is_valid():
    import re
    #Perform some regex matches and stuff
    if (above re matches succeed):
        import module1
        #Process my stuff here using module1 here
        #and so on importing modules only when they are required

Which one of these is recommended and would have best performance on the website?

MohitC
  • 4,541
  • 2
  • 34
  • 55

2 Answers2

5

Don't do this.

There is no reason to import in the middle of the code like this. Imports are only done once; since it's almost certain that at some point your code will follow the is_valid path, you will need that import, so there is no benefit in holding off the import until then.

In fact, that could potentially make it less performant; rather than all the imports being done when the process starts up, you're doing it in the middle of someone's request.

But either way, the difference would be negligible anyway. For the sake of readability, put your imports where they belong, at the top.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks, I dont have any idea of internal workings here, but wont the import be performed again when user clicks submit button on form? Isnt the views.py called again? – MohitC May 25 '16 at 10:57
  • 1
    Yes the view *function* is called again. But that wouldn't trigger the imports to be done again; they are global to the file. And even if they were, Python does not re-import a module when it has already been imported. – Daniel Roseman May 25 '16 at 10:59
  • Thanks that makes it a lot clear. – MohitC May 25 '16 at 10:59
0

Import modules at the top of the file are totally fine and it's a recommended way to do so.

It does not add any runtime overhead because imports have done only ones, not at every request (like in PHP).

dizballanze
  • 1,267
  • 8
  • 18