Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import inside a function: is memory reclaimed upon function exit?

Linked questions:

  • python - import at top of file vs inside a function
  • Should Python import statements always be at the top of a module?

If an import statement is inside a function, will the memory occupied by it get reclaimed once the function exits? If yes, is the timing of the reclamation deterministic (or even -ish)?

def func():
    import os
    ...
    # function about to exit; will memory occupied by `os` be freed?

If anyone has knowledge on the behavior of micropython on this topic, bonus points.

like image 701
Bob Avatar asked Nov 16 '25 09:11

Bob


1 Answers

The first import executes the code in the module. It creates the module object's attributes. Each subsequent import just references the module object created by the first import.

Module objects in Python are effectively singletons. For this to work, the Python implementation has to keep the one and only module instance around after the first import, regardless of the name the module was bound to. If it was bound to a name anyway, as there are also imports of the form from some_module import some_name.

So no, the memory isn't reclaimed.

No idea about Micropython, but I would be surprised if it changes semantics here that drastically. You can simply test this yourself:

some_module.py:

value = 0

some_other_module.py:

def f():
    import some_module
    some_module.value += 1
    print(some_module.value)

f()
f()

This should print the numbers 1 and 2.

like image 117
BlackJack Avatar answered Nov 18 '25 02:11

BlackJack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!