Reputation: 11
I want to know if I can create a function that within it's arguments I can define what function to use for something else? eg:
def askquestion(functionname):
userinput == str(input("Are you sure you want to run this? <y/n> "))
if userinput = "y":
functionname()
elif userinput == "n":
print("returning to main menu")
else:
print("That is not a valid input!")
I dont know if I explained that very well but if you could help me out with this it would be great.
Upvotes: 1
Views: 134
Reputation: 1122352
Yes, you can. Just pass in the function object:
def foo():
# do foo
def bar():
# do bar
askquestion(foo) # will run foo when `y` is typed.
Python functions are first-class objects, they are assigned to whatever name they are defined as to begin with but you can bind them to other names too.
You can, for example, store them in a mapping, then look up functions in the mapping based on another variable altogether:
map = {
'spam': foo,
'eggs': bar,
}
askquestion(map[anothervar])
Within askquestion
, functionname
is then bound to whatever function object you passed in. Adding ()
after the name invokes the function.
You can pass in arguments too, but then all functions you pass in have to have the same signature. You could wrap the function in a lambda
or other function object to pass in extra arguments, or take a look at functools.partial()
to generate callables with pre-defined arguments.
Upvotes: 4