Reputation: 45
Maybe this is a silly question but I am struggling with it and I can't manage to find a clear explanation on the internet.
So I want to write a module with a function in it. I would like this function to take another function as argument, do something to the output of the argument-function and return it.
In code what I would like to do is:
from my_module import my_function
output = stuff.my_function() # stuff = what my_function accepts as argument
Since there are many in build python methods that do this I believe it is possible but I have no idea how. I tried a few ways but none work.
Thank you in advance for the help
Upvotes: 0
Views: 448
Reputation: 322
file my_module.py
def my_function():
return something
file current.py
from my_module import my_function
def a_function(x):
does something
return y
output = a_function(my_function())
Upvotes: 0
Reputation: 11113
What you want to do is pass a_function
as an argument to my_function
and get a modified function back.
Here's a simple example:
In [1]: def add_one(f):
...: def f_plus_1(*args, **kwargs):
...: return f(*args, **kwargs) + 1
...: return f_plus_1
...:
In [2]: def multiply(a, b):
...: return a * b
...:
In [3]: multiply_and_add_one = add_one(multiply)
In [4]: multiply(5, 3)
Out[4]: 15
In [5]: multiply_and_add_one(5, 3)
Out[5]: 16
Here we use *args
and **kwargs
to pass through any arguments we get to the original function.
Upvotes: 0
Reputation: 30288
Functions are first class citizen's in python so you pass functions by name without the ()
, then you can call that function by using the ()
e.g.:
from my_module import my_function
def a_function(x):
y = x()
return y
output = a_function(my_function)
Upvotes: 4