I've been playing with the setuptools pkg_resources module to load plugin functions via entry points. It seems that once an entry point has been loaded, the specific distribution used to get that entry point is now "active" (and therefore saved in pkg_resources.working_set
, sys.path
, and a handful of other locations).
My question: is there any standard way to "deactivate" a distribution? I don't know much of the internal details of the module loading that goes on behind the scenes, but I have hacked together the following function which seems to work:
def deactivate(dist):
from pkg_resources import working_set
from sys import path, modules, path_importer_cache
distpath = working_set.by_key.pop(dist).location
working_set.entry_keys.pop(distpath)
working_set.entries.remove(distpath)
path.remove(distpath)
for name, mod in modules.items():
try:
if mod.__file__.startswith(distpath):
modules.pop(name)
except:
pass
If there is no standard way that I have missed, will the function above work as my limited testing indicates? or is it missing some internal workings of system path or pkg_resources that will lead to weird bugs down the road?
Background I'm trying to use entry points and eggs to allow dynamic loading of different versions of a module at a user's discretion. Deactivation only becomes an issue if you want to allow the user to switch versions without restarting the main script, since after loading the first version you can only use that version.