Reputation: 5355
Say I have a file functions.py
containing
def some_function():
return "something"
def some_other_function():
return "something else"
I'm trying to create a dictionary in another file, load_functions.py
, with keys being the function-names from functions.py
and the items being the actual function e.g:
import functions
useable_functions = [f for f in dir(functions) if "__" not in f] #Get all functions to be used
function_dict = TO_BE_IMPLEMENTED
print(function_dict)
#{"some_function":some_function,
#"some_other_function":some_other_function}
func = function_dict["some_function"]
func()
# "something"
Is it by all means doable?
Upvotes: 1
Views: 971
Reputation: 1071
Take a look at the inspect
module.
Say you have your functions.py
module.
To get all functions from it, use this:
import inspect
import functions # your module
elements = inspect.getmembers(functions, inspect.isfunction)
element_dict = dict(elements)
The call will return all the function members of the functions.py
module as a list of (name, value)
pairs sorted by name. Note it will also include lambdas.
Then, I use dict()
to convert the (name, value)
pairs to a dict.
https://docs.python.org/3/library/inspect.html
Upvotes: 3