1

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.

2

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if the function foo accepts some arguments? say def foo(blah, blahblah)
@ansh0l: You can pass in arguments, yes; it's just a function object bound to a different name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.