0

Code in module_a:

varA=10

class ClassX:
    def fn1():
        return varA

Code in Flask_api:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    import module_a    # or from module_a import varA
    module_a.varA += 1     # or varA+=1
    return module_a.varA

When running on development server, there maybe 1 process and 1 thread handling all request. However, on production, since each flask endpoint invocation can spin up in a new process or a new thread, then, I am curious to know if there are any things I need to be careful about?

For example: It is not process safe and thread safe.

Also is there difference between doing imports in function vs outside.

variable
  • 8,262
  • 9
  • 95
  • 215

1 Answers1

1

The reasons to do an import inside a function instead of on the top level are usually:

  • to defer the initial import e.g. because you rarely need it (and thus want to avoid importing it during initial startup). Not very common though, but if you import e.g. some expensive error handling module which you don't expect to need (because you don't expect errors) it may make sense.

  • to avoid circular dependency issues. If module A import module B, and module B imports module A, you may end up not being able to import either of them because they depend on each other. Moving the import into a function avoids this.

In terms of general performance and threading it doesn't matter: As soon as you import a module for the first time (from anywhere), it is added to sys.modules. So any further import of it will just return the entry from there instead of doing the actual import again.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636