This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 8 years ago.
s = "func"
Now suppose there is function called func.
How can i call in Python 2.7 call func when the function name is given as a string?
The safest way to do this:
In [492]: def fun():
.....: print("Yep, I was called")
.....:
In [493]: locals()['fun']()
Yep, I was called
Depending on the context you might want to use globals() instead.
Alternatively you might want to setup something like this:
def spam():
print("spam spam spam spam spam on eggs")
def voom():
print("four million volts")
def flesh_wound():
print("'Tis but a scratch")
functions = {'spam': spam,
'voom': voom,
'something completely different': flesh_wound,
}
try:
functions[raw_input("What function should I call?")]()
except KeyError:
print("I'm sorry, I don't know that function")
You can also pass arguments into your function a la:
def knights_who_say(saying):
print("We are the knights who say {}".format(saying))
functions['knights_who_say'] = knights_who_say
function = raw_input("What is your function? ")
if function == 'knights_who_say':
saying = raw_input("What is your saying? ")
functions[function](saying)
else:
functions[function]()
def func():
print("hello")
s = "func"
eval(s)()
In [7]: s = "func"
In [8]: eval(s)()
hello
Not recommended! Just showing you how.
you could use exec. Not recommended but doable.
s = "func()"
exec s
You can execute a function by passing a string:
exec(s + '()')
Related
This question already has an answer here:
Eval/Exec with assigning variable - Python
(1 answer)
Closed 3 years ago.
First of all, yes I know what I'm doing is bad. It's part of a hacky project that I'm trying for fun.
In Python 2.7, you could do this:
def myfunc():
exec('a=3')
print('Result: a = {}'.format(a))
myfunc()
And get Result: a = 3
Not so in Python 3.6, where you'll get NameError: name 'a' is not defined.
I can try to work around this by doing:
def myfunc():
exec('globals()["a"]=3')
print('Result: a = {}'.format(a))
myfunc()
Which in Python 3.6 gives the desired Result: a = 3 (and yes, has dangerous consequences by modifying globals). But of course it fails in the following case:
def myfunc():
a=2
exec('globals()["a"]=3')
print('Result: a = {}'.format(a))
myfunc()
Where I get Result: a = 2. Swapping in exec('a=3') here will also give Result: a = 2.
Question: Is there any hack in Python 3 that effectively allows me to assign to a variable in a function body?
def myfunc():
exec('a=3', locals(), globals())
print('Result: a = {}'.format(a))
myfunc()
This question already has answers here:
Can one function have multiple names?
(3 answers)
Closed 5 years ago.
I wold like to use same method but two different names.
For example:
def func(a):
print a
def func2(a):
print a
n= "yes"
func(n)
func2(n)
answer should be:
"yes"
"yes"
Would there be any way I can do:
def fun(a) or func2(a):
print a
or something like this?
Python functions are just objects, you can assign one to another name:
def fun(a):
print a
func2 = fun
Now the names func2 and fun reference the same function object, you can call it through either name.
def func(a):
print("a")
n= "yes"
def fun(a):
func(a)
func(n)
This question already has answers here:
Python function as a function argument?
(10 answers)
Closed 6 years ago.
def example(function):
if input() == "Hello there!":
#at this point I want to call the function entered in the tuples
an example of what I mean:
def example(function):
if input() == "Hello there!":
#do the function here
def Printer(What_to_print):
print(What_to_print + "Just an example")
example(Printer)
Is this possibe and are there drawbacks in doing this?
Yes. It is possible.
def example(function):
if input() == "Hello there!":
function("Hello there!") # invoke it!
Actually you can pass def functions and lambda functions as parameters and invoke them by () syntax.
In python, functions are objects like any other common types, like ints and strs. Therefore, there is no problem with a function that receives another function as an argument.
>>> def pr(): print ('yay')
>>> def func(f): f()
>>> isinstance(pr, object)
True
>>> isinstance(int, object)
True
>>> func(pr)
yay
>>>
def example(function, what_to_print):
if raw_input() == "Hello there!":
function(what_to_print)
def printer(what_to_print):
print(what_to_print + "Just an example")
example(printer, "")
This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 7 years ago.
It accepts the inputs ok, but doesn't go on to the if statement. Can I not define a variable in a function argument?
def maximum(one = int(input("Enter first Number: ")),
two = int(input("Enter second Number: "))):
if one > two:
return one
else:
return two
maximum()
You can "define variables" in the argument list. The problem is that the expression is only evaluated once, when the function is declared.
To give an example, in this interactive (IPython!) session I'm declaring two functions. Note that "Doing something" is only printed once, just as I declare test():
In [86]: def something():
....: print "Doing something"
....: return 10
....:
In [87]: def test(x=something()):
....: print "x is %s" % x
....:
Doing something
In [88]: test()
x is 10
In [89]: test()
x is 10
For the above reason, the following pattern is pretty common for default arguments in Python, try to use it in your function.
def foo(arg=None):
if arg is None:
arg = "default value" # In your case int(input(...))
Don't use default argument's values in such way. They evaluated only once during function creation. So your function will always receive the same input that will be equal to first time received data.
Default value for the parameters is evaluated when the def statement they belong to is executed (that is they are only executed when the function is defined) .
They are not recalculated when the function they belong to is called.
Example -
>>> def hello(one = print("Hello")):
... print("Bye")
...
Hello
>>> hello()
Bye
>>>
I want to basically turn a list element into a function with
the do function. This way any pre-written funcction i can call by just use a
do(list[x]).
What im trying to do is a function that takes away the quotes of a list element and then executes the function that is in that list element.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
#I think the problem is here
funs = ['func()','func1()','func2()']
print ''.join(funs[0])
do(''.join(funs[0]))
Edit:
What im trying to do is a function that takes away the quotes of a
list element and then executes the function that is in that list
element
You don't need the extra functions, and you don't need to turn them into a string either:
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
funcs = [func, func1, func2]
for function in funcs:
function()
Well, it basically works like this. Note that the list contains the functions themselves, not a string.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
funcs = [func, func1, func2]
for function in funcs:
do(function)
Output:
python
is
awesome
EDIT: If you do want the list to contain the functions' names as strings, use eval():
funcs = ['func', 'func1', 'func2']
for function in funcs:
do(eval(function))
If you really want to execute arbitrarily named functions from a list of names in the current global/module scope then this will do:
NB: This does NOT use the potentially unsafe and dangerous eval():
Example:
def func():
return "python"
def func1():
return "is"
def func2():
return "awesome"
def do(func_name, *args, **kwargs):
f = globals().get(func_name, lambda : None)
if callable(f):
return f(*args, **kwargs)
funs = ["func", "func1", "func2"]
print "".join(funs[0])
print "".join(map(do, funs))
Output:
$ python foo.py
func
pythonisawesome
You can also individually call "named" functions:
>>> do(funs[0])
python
Note the implementation of do(). This could also be applied more generically on objects and other modules too swapping out globals() lookups.
As the people above have said the best way is to define a dictionary of functions, as functions are objects in python this is possible
def One():
pass
def Two():
pass
functions = {"ONE":One, "TWO":Two}
You can then call it like this:
functions[input]()
If you want to give true control to the user (And I DO NOT recommend doing this) you could use the eval function.
eval(input+"()")