Skip to content

Instantly share code, notes, and snippets.

@BinarSkugga
Created July 30, 2021 16:54
Show Gist options
  • Save BinarSkugga/c281cbbe36e7f11bc0fd143ea1bb4dd4 to your computer and use it in GitHub Desktop.
Save BinarSkugga/c281cbbe36e7f11bc0fd143ea1bb4dd4 to your computer and use it in GitHub Desktop.
Providing arguments to a module when importing
import utils
test = utils.inject('test')
foo = utils.inject('foo')
assert test==6
assert foo['value'] == 56
print(__inject__)
# Executing this will import 'imported.py' and execute the assert successfully
import utils
spec = utils.get_module_spec('imported')
utils.exec_module(spec, test=6, foo={'value': 56})
import importlib.util
import inspect
def _caller_locals():
frame = inspect.currentframe()
return inspect.getouterframes(frame, 2)[2][0].f_locals
def inject(name: str):
locals = _caller_locals()
if '__inject__' not in locals:
raise NameError('No injected values were added to this module.')
injected_params = locals['__inject__']
if name not in injected_params:
raise KeyError(f'No value was injected inside the \'{name}\' key.')
return injected_params[name]
def get_module_spec(module_name: str):
module_spec = importlib.util.find_spec(module_name)
return module_spec
def exec_module(module_spec, **params):
module = importlib.util.module_from_spec(module_spec)
# Inject provided dict
setattr(module, '__inject__', params)
module_spec.loader.exec_module(module)
return module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment