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)
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
How to pass functions with arguments as parameter to another function in python with function name as a string?
Replace eval(function_name)(img,parameter)
with:
globals()[function_name](img,parameter)
Note that your desired function should be in the same module in my answer, if it is not, read this link or This about globals
and locals
in python to find the best thing for your problem.
Also, you can access a function of another module with getattr
, like this:
getattr(module, func)(*args, **kwargs)
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()
Best Way to Pass Arguments from One Function to Another in Python
do_lots_of_stuff("Bob","Mary",activity_1='run',activity_2='jump', eat_fruit_args=["John"], eat_fruit_kwargs={"a_number": 5, "a_fruit": "apples"}):
eat_fruit(*eat_fruit_args, **eat_fruit_kwargs)
return(f'''{a} and {b} {activity_1} and {activity_2}''')
You can pass and forward arguments and keyword arguments. Arguments are in the form of a list. Keyword arguments (kwargs) are in the form of a dictionary, with the key as a string, and the value as the correlating keyword value.
Python: passing a function with parameters as parameter
Why not do:
big(lite, (1, 2, 3))
?
Then you can do:
def big(func, args):
func(*args)
Pass all arguments of a function to another function
The standard way to pass on all arguments is as @JohnColeman suggested in a comment:
class ClassWithPrintFunctionAndReallyBadName:
...
def print(self, *args, **kwargs):
if self.condition:
print(*args, **kwargs)
As parameters, *args
receives a tuple of the non-keyword (positional) arguments, and **kwargs
is a dictionary of the keyword arguments.
When calling a function with *
and **
, the former tuple is expanded as if the parameters were passed separately and the latter dictionary is expanded as if they were keyword parameters.
Related Topics
Python Selenium Click on Button
Googletrans Stopped Working with Error 'Nonetype' Object Has No Attribute 'Group'
How to Add Custom Methods/Attributes to Built-In Python Types
Error: (-215) !Empty() in Function Detectmultiscale
How to Zip Two Differently Sized Lists, Repeating the Shorter List
Convert Pandas.Series from Dtype Object to Float, and Errors to Nans
Why Do Integers in Database Row Tuple Have an 'L' Suffix
Making a String Out of a String and an Integer in Python
Find Shortest Matches Between Two Strings
How to Write a Python Module/Package
Run Function from the Command Line
Installing Python Packages from Local File System Folder to Virtualenv with Pip
How to Change the Figure Size of a Seaborn Axes or Figure Level Plot