Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling unknown Python functions

Tags:

python

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
like image 565
Teifion Avatar asked Apr 13 '09 17:04

Teifion


People also ask

Can we define Python function to accept unknown number of arguments?

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 do you call a function in Python?

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.

Is there a call function in Python?

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():

Can I call function from list in Python?

Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.


2 Answers

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.

like image 196
Anthony Towns Avatar answered Oct 07 '22 17:10

Anthony Towns


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)
like image 45
nosklo Avatar answered Oct 07 '22 19:10

nosklo