0

I perform the import module operation in exec,After the foo function is executed, the pandas module memory is not released,I want to be able to clear the memory of all imported modules in the function after the function finishes,help。

Pay attention to: Module names are not fixed

from time import sleep


def foo():
    code = """import pandas as pd"""
    exec(code)


if __name__ == '__main__':
    foo()
    sleep(100)
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Related but not an answer: https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module and something that implies it might not be easy to do: https://stackoverflow.com/questions/21630060/unloading-a-module-in-python-3-x-not-the-same-as-re-loading (but the comment on that ones answer implies it can be done). – Pam Oct 11 '22 at 09:32
  • It is rather unusual to import a module in a function like this. As it's not how modules are intended to be used there may be issues with scoping and memory management. I would try and avoid this if possible. Generally all modules are imported at the start of the script. I can't think of a good reason not to do this unless you're really limited on memory, and even then there are likely better approaches like using very limited submodules. – Ari Cooper-Davis Oct 11 '22 at 09:35
  • I want to do functionality similar to jupyter, code provided by the user, but I do not want to execute the end of the code for my service memory growth – XieZhiPeng Oct 11 '22 at 09:42

0 Answers0