What?
I'm trying to import all the functions from a file (given it's path) to a list/dict
At the moment I'm using what was said here and here. The result is this
import inspect
import importlib.util
def functions_from_file(path_to_module):
spec = importlib.util.spec_from_file_location("my_module",
path_to_module)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
custom_functions = inspect.getmembers(module, inspect.isfunction)
return dict(custom_functions)
This, at least to me, seems very convoluted. Is there a better/cleaner way to do so?
Why?
The reason I'm doing so is that I want the user to be able to specify a file containing a list of functions that will be executed in the middle of my code. So the file could look something as:
def fun1(my_dict):
my_dict['foo'] = my_dict['bar']*2
def fun2(my_dict):
my_dict['baz'] = my_dict['foo'] - my_dict['bar']
and then in my code there should be something like
for fun in functions_list:
fun(my_dict)