I can only imagine one way that imports could be abused to leak memory; You could dynamically create and import modules of arbitrary name (say, for the purpose of creating a plugin system); use them once and stop using them. If you did this through the normal import machinery, ie with __import__(variable_module_name)
, those modules would be added to sys.modules
and even though they will not be used any further.
The solution is well, don't do that. If you are really creating a plugin system, then dynamic imports of that sort are probably fine, since the plugins would get re-used. If you really need to use dynamically generated, single use code; use eval
.
If you really, really need to use importing on dynamically generated code (say, for automated testing), then you probably do need to poke around in sys.modules
to erase the modules that you imported. Here's a nice article explaining how to do something like that.