I can only imagine how imports could be abused to leak memory; You can dynamically create and import arbitrary name modules (for example, to create a plug-in system); use them once and stop using them. If you did this using the usual import mechanism, i.e. Using __import__(variable_module_name) , these modules will be added to sys.modules and will not even be used further.
The solution is good, do not do it. If you are really creating a plugin system, then dynamic imports of this kind are probably great, as plugins will be reused. If you really need to use a dynamically generated one-time code; use eval .
If you really really need to import dynamically generated code (say, for automatic testing), then you probably need to poke into sys.modules to erase the modules you imported. Here is a good article explaining how to do this.
SingleNegationElimination
source share