0

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)
Luca
  • 1,610
  • 1
  • 19
  • 30
  • What about adding the directory to `sys.path` and then importing it normally? Otherwise, have a look at using a plugin liibrary, something like [pluginBase](http://pluginbase.pocoo.org/) sounds like it could do what you're after. – Holloway Oct 07 '19 at 10:04

1 Answers1

-1

Have you tried importing the py file as a module in your target file?

See Documentation Here

Nikhil Gupta
  • 1,436
  • 12
  • 15
  • I don’t know neither the name of the file, its path, nor the name of the functions in it a priori. – Luca Oct 06 '19 at 16:33
  • OK, got it. But your original post mentioned that you are given the file's path. If you know the directory where the file resides, you can still list all the functions in the module using the information here: https://stackoverflow.com/questions/139180/how-to-list-all-functions-in-a-python-module. Hope this helps! – Nikhil Gupta Oct 07 '19 at 14:27
  • Your link shows how to import a module and show the name of the methods as string. Moreover I need to hard code the path to the module and cannot leave it as an input. My question is way beyond this. You can try running the code snippet I posted to understand the wanted behaviour. – Luca Oct 07 '19 at 14:43