This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.
How do I call a function from a string, i.e.
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
Well, using *args in a function is Python's way to tell that this one will: Accept an arbitrary number of arguments. Pack the received arguments in a tuple named args. Note that args is just a name and you can use anything you want instead.
How to call a function in python? Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. >>> greet('Paul') Hello, Paul.
Function Calling in PythonOnce a function is created in Python, we can call it by writing function_name() itself or another function/ nested function. Following is the syntax for calling a function. Syntax: def function_name():
Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.
You can use the python builtin locals() to get local declarations, eg:
def f():
print "Hello, world"
def g():
print "Goodbye, world"
for fname in ["f", "g"]:
fn = locals()[fname]
print "Calling %s" % (fname)
fn()
You can use the "imp" module to load functions from user-specified python files which gives you a bit more flexibility.
Using locals() makes sure you can't call generic python, whereas with eval, you could end up with the user setting your string to something untoward like:
f = 'open("/etc/passwd").readlines'
print eval(f+"()")
or similar and end up with your programming doing things you don't expect to be possible. Using similar tricks with locals() and dicts in general will just give attackers KeyErrors.
how do you not know the name of the function to call? Store the functions instead of the name:
functions_to_call = [int, str, float]
value = 33.5
for function in functions_to_call:
print "calling", function
print "result:", function(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With