Home > Software engineering >  Python / Import module within a defined function?
Python / Import module within a defined function?

Time:08-06

would you recommend using the import outside of the function or within is fine?

Any recommendations/critics welcome. Thanks

import time
import datetime

# Time Since 
def time_since(since):
    now = datetime.now()
    unixtime = calendar.timegm(now.utctimetuple())
    since = unixtime - 60 * 60 * 24 * 20


# Execute code every 60 sec 
def autorun(seconds):
    import time
    starttime = time.time()
    while True:
    print("tick")
    time.sleep(seconds - ((time.time() - starttime) % seconds))

CodePudding user response:

Imports should be at the top of the file unless you have a circular dependency. In that case, to fix it we have to import it within the function where we want to use it.

To read more about circular import go through this.

CodePudding user response:

For this use case just import once at the start of the file; it's not going to change the performance by any tangible amount.

One reason to include the import statement within the function is to lazy load the import, i.e., the module is only loaded when the function is called and not on start up of the module.

This can be beneficial for some use cases, we can see this in the Python source code of the Counter module within collections package: Counter source code

heapq is lazy loaded to speedup Python startup time

Also see this discussion on how Python deals with attempts to import a module multiple times: https://stackoverflow.com/a/37077911/15981783.
tl;dr it doesn't, if module is imported python just gets module object.

  • Related