How to determine if one module was loaded before or after another

The use case for this is that the library I am writing uses Python modules to store data that is heavily interleaved with code as needed; each "database record" is a subclass of a class defined in a higher module. There is also a module that contains functions for finding this "database" which uses introspection to find records based on user-defined filters and only checks for modules that have already been imported. It is usually configured to return the first result it sees.

This library will also want to interact with user provided database modules. A custom module might want to "override" an entry from another module, and I would like the order in which the modules are checked out clearly. Ideally, I would like the entries to be checked from a recently imported, albeit recently imported.

How can I sort the content sys.modules

in the order in which they were imported?

+1


source to share


2 answers


You can implement rpattiso idea as

data_modules = []
def reg_import(modname):
    mod __import__(modname)
    data_modules.append(mod)
    return mod

      

Then search for data_modules in reverse order. This requires users to import and use reg_imports, but it gives you a clean list of data modules to search for. A possible alternative would be before importing the user.



from collections import OrderedDict
import sys

od = OrderedDict()
od.update(sys.modules)
sys.modules = od

      

This will be automatic from a user point of view, but will mix data modules with other modules and require more processing to separate them. I would go with a registration function.

0


source


Depending on the order in which modules are imported, this is not very common and suggests that this is the wrong approach. Instead, the library should include functionality as needed so that the user can override certain entries.



This is also in line with Python's thinking in software development: explicit is better than implicit, and whatever the user wants to override must be clearly stated and passed to the library. It may sound cumbersome, but it requires the least amount of magic and is best maintained in the long run.

0


source







All Articles