Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
already_imported = name in sys.modules
mod = _orig__import(name, *args, **kwargs)
# Optimization: worth processing only when importing was done for the first time
if not already_imported:
lgr.log(1, "Module %s was imported", name)
self.process(name, mod)
return mod
__import.__duecredited__ = True
lgr.debug("Assigning our importer")
__builtin__.__import__ = __import
# TODO: retrospect sys.modules about possibly already loaded modules
# which we cover, so they need to be decorated at this point
else:
lgr.warning("Seems that we are calling duecredit_importer twice."
" No harm is done but shouldn't happen")
lgr.debug("Request to process known to injector module %s", name)
try:
mod = sys.modules[name]
except KeyError:
lgr.warning("Failed to access module %s among sys.modules" % name)
return
# go through the known entries and register them within the collector, and
# decorate corresponding methods
# There could be multiple records per module
for obj_path, obj_entry_records in iteritems(self._entry_records[name]):
try:
parent, obj_name, obj = find_object(mod, obj_path)
except KeyError as e:
lgr.warning("Could not find %s in module %s: %s" % (obj_path, mod, e))
continue
# there could be multiple per func
for obj_entry_record in obj_entry_records:
entry = obj_entry_record['entry']
# Add entry explicitly
self._collector.add(entry)
# TODO: decorate the object (function, method) which will also add entries
decorator = self._collector.dcite(entry.get_key(), **obj_entry_record['kwargs'])
setattr(parent, obj_name, decorator(obj))
def deactivate():
if '_orig__import' not in globals():
lgr.warning("_orig_import is not known, so we haven't decorated default importer yet."
" Nothing TODO")
return
lgr.debug("Assigning original importer")
global _orig__import
__builtin__.__import__ = _orig__import