How to pass function as an argument to another function, without running it automatically
The problem is that you are calling your function when you're trying to pass it as a parameter. Instead of passing it as someFunction(...)
, pass it as someFunction
.
e.g.
a = testObject("testName2", someFunction )
instead of what you have. This will pass the function 'object', ready to be called. Then, inside the other function, simply do:
def testObject(name, funct):
if name == "testName":
b = funct([0,0,0], 1, 6)
I assume you'd want to pass the values as different arguments, as I assume these aren't constants, but this should be enough to guide you.
If you want to pass it in with arguments already set, I'd definitely give a look into functools.partial, but keep in mind that it might become a bit messy.
For partial:
from functools import partial
partial_function = partial(someFunction, [0,0,0], 1, 6)
a = testObject("testName2", partial_function )
------
def testObject(name, funct):
if name == "testName":
b = funct()
passing functions and its arguments to another function
Something like this would work:
def no_arg():
return 5
def one_arg(x):
return x
def multiple_args(x, y):
return x * y
def function_results_sum(*args, **kwargs):
result = 0
for func in args:
result += func(*kwargs[func.__name__])
return result
Output:
function_results_sum(
no_arg, one_arg, multiple_args,
no_arg=(),
one_arg=(23, ),
multiple_args=(1,5))
33
The only difference between what you are asking is that you have to put args in a tuple to then unpack as args to pass in later.
If you dont want to have to supply anything for no argument functions, you can double check if the func name is in kwargs:
def function_results_sum(*args, **kwargs):
result = 0
for func in args:
if func.__name__ i kwargs:
result += func(*kwargs[func.__name__])
else:
result += func()
return result
Passing functions with arguments to another function in Python?
Do you mean this?
def perform(fun, *args):
fun(*args)
def action1(args):
# something
def action2(args):
# something
perform(action1)
perform(action2, p)
perform(action3, p, r)
How do I pass variables across functions?
This is what is actually happening:
global_list = []
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to global_list
useTheList(global_list)
main()
This is what you want:
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)
main()
You can even skip the temporary returned_list
and pass the returned value directly to useTheList
:
def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())
Function as an argument of another function
A function is an object just like any other in Python. So you can pass it as argument, assign attributes to it, and well maybe most importantely - call it. We can look at a simpler example to understand how passing a function works:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def operate(func, a, b):
return func(a, b)
a = 4
b = 5
print(operate(add, a, b))
print(operate(sub, a, b))
operate(print, a, b)
And this prints out:
9
-1
4 5
That is because in each case, func
is assigned with the respective function object passed as an argument, and then by doing func(a, b)
it actually calls that function on the given arguments.
So what happens with your line:
return x(x(a, b), x(a, b))
is first both x(a, b)
are evaluated as add(4, 5)
which gives 9
. And then the outer x(...)
is evaluated as add(9, 9)
which gives 18
.
Passing a function argument through another function in Python
def function(classifier, classifier_argument, list_of_parameters):
args = {classifier_argument:list_of_parameters}
classifier(**args)
classifier = someClassifier # Note - you need to reference the function itself, not call it!
classifier_argument = 'someArgument'
list_of_parameters = [0,1,2,3,4,5]
function(classifier,classifier_argument,list_of_parameters)
A couple of points here: you have to unpack the arguments list, and you need to pass in the classsifier function without calling it.
How do I pass a method as a parameter in Python
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self
parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
Note: I believe a __call__()
method does exist, i.e. you could technically do methodToRun.__call__()
, but you probably should never do so explicitly. __call__()
is meant to be implemented, not to be invoked from your own code.
If you wanted method1
to be called with arguments, then things get a little bit more complicated. method2
has to be written with a bit of information about how to pass arguments to method1
, and it needs to get values for those arguments from somewhere. For instance, if method1
is supposed to take one argument:
def method1(self, spam):
return 'hello ' + str(spam)
then you could write method2
to call it with one argument that gets passed in:
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
or with an argument that it computes itself:
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
You can expand this to other combinations of values passed in and values computed, like
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
or even with keyword arguments
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
If you don't know, when writing method2
, what arguments methodToRun
is going to take, you can also use argument unpacking to call it in a generic way:
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
In this case positional_arguments
needs to be a list or tuple or similar, and keyword_arguments
is a dict or similar. In method2
you can modify positional_arguments
and keyword_arguments
(e.g. to add or remove certain arguments or change the values) before you call method1
.
Related Topics
Stopping a Thread After a Certain Amount of Time
Target Wsgi Script Cannot Be Loaded as Python Module
How to Get Tkinter Canvas to Dynamically Resize to Window Width
Generating File to Download with Django
Deleting Multiple Columns Based on Column Names in Pandas
No Module Named 'Pandas._Libs.Tslibs.Timedeltas' in Pyinstaller
Python Requests.Get() Returns Improperly Decoded Text Instead of Utf-8
Most Pythonic Way to Interleave Two Strings
How to Use a Custom Comparison Function in Python 3
Pythonic Way to Create Union of All Values Contained in Multiple Lists
How to Install Pip for Python 3 on MAC Os X
Opencv Python Rotate Image by X Degrees Around Specific Point
Python Super() Raises Typeerror
Conversion of Strings Like \\Uxxxx in Python
Unbuffered Stdout in Python (As in Python -U) from Within the Program