I’m working on a project where users can define functions (to do things to a Redis DB, though it probably doesn’t matter) in a file. These files will live in a folder with lots of other similar files. Think of building a library of functions that act on a Redis db like custom Redis commands. It might be something similar to homebrew as far as the ability to add new functions.
As it is currently written, the person using the script will provide a string representation of the function they want to run and the script will find it and run it. I’d like for the main script to be able to walk the files in this library directory and make all of the functions in each file available to the main script.
I know how to call a function from a string of the function name. What I cannot figure out is how to walk the files in this directory and import the functions or make the functions available to be called.
Right now, I only have it working with functions defined in the main script using code like this where command is a string of a function name passed from the command line:
possibles = globals().copy()
possibles.update(locals())
custom_method = possibles.get(command)
if custom_method:
print custom_method(r)
There are some other questions in my head here like maybe I should force all library methods to live in a class with the same name of the file? Would that, or something similar, make what I’m trying to do easier? Maybe the imp module and find_module can help?
A follower on Twitter proposed this solution: https://gist.github.com/1853553
The importlib module is what you’re looking for along with
osandos.pathOnce you get the files loaded up, you can use the inspect module and/or
dir()to build up a list of available functions/classes/etc.