Home > other >  Python function as argument
Python function as argument

Time:03-23

I have a problem with pass other function as parametr to another.

I have function marks_as_done and delete_task in separate file

tasks.py

def mark_as_done(conn):
    print("marking")
    try:
        id = int(input("Enter id of task: "))
        command = f"UPDATE tasklist SET finish_date='{dt_string}', status='True' WHERE id={id}"
        db_execute(command, conn)
    except ValueError:
        print("Wrong! Enter only number.")

def delete_task(conn):
    print("deleting")
    try:
        id = int(input("Enter id of task: "))
        command = f"DELETE from tasklist WHERE id={id}"
        db_execute(command, conn)
    except ValueError:
        print("Wrong! Enter only number.")

I created function what_next with where some arguments are functions.

main.py

def what_next(func1, func2, conn, option1, option2):
    print("Starting what next function")
    try:
        x = int(input(f"\n1 - {option1}\n2 - {option2}\n3 - Back to menu\n4 - Exit from app\nChoose what you want to do: "))
        print(f"First This is x from what next function: {x}")
        match x:
            case 1:
                print(f"This is x from what next function: {x}")
                func1
            case 2:
                print(f"This is x from what next function: {x}")
                func2
            case 3:
                print(f"This is x from what next function: {x}")
                mainFunc()
            case 4:
                print(f"This is x from what next function: {x}")
                conn.close()
                sys.exit()
            case _:
                print("Number out fo range.")
                mainFunc()
    except ValueError:
        print("Wrong! Enter only number.")

I call this function in main function:

main.py

def mainFunc():
    print("\n--------------------------Welcome in ToDoList app!--------------------------")
    while True:
        print("""\nMenu:\n1 - Add task\n2 - Show active tasks\n3 - Show tasks history\n4 - Search taks\n5 - Exit\n""")
        try:
            choose = int(input("Choose what you wany to do: "))
            match choose:
                case 1:
                    while True:
                        add_task(conn)
                        what_next(conn, "Continue", "", None, None)
                case 2:
                    while True:
                        show_active_task(conn)
                        #what_next_temp(conn)
                        what_next(mark_as_done(conn), delete_task(conn), conn, "Mark as done", "Delete task")
                case 3:
                    show_task_history(conn)
                    what_next(conn, "Continue", "", None, None)
                case 4:
                    pass
                case 5:
                    conn.close()
                    sys.exit()
                case _:
                    print("Number out fo range.")
                    mainFunc()
        except ValueError:
            print("Wrong! Enter only number.")

I this case when i choose "2" in main funcion and enter in case 2, show_active_task(conn) function is call properly but after instead of what_next, marks_as_done and delete_task are executed and after what_next

Update

Finally i change the what_next funtion to this:

def what_next(func1, func2, conn, option1, option2):
    print("Starting what next function") 
    try:
        x = int(input(f"\n1 - {option1}\n2 - {option2}\n3 - Back to menu\n4 - Exit from app\nChoose what you want to do: "))
        print(f"First This is x from what next function: {x}")
        match x:
            case 1:
                print(f"This is x from what next function: {x}")
                func1(conn)
            case 2:
                print(f"This is x from what next function: {x}")
                func2(conn)
            case 3:
                print(f"This is x from what next function: {x}")
                mainFunc()
            case 4:
                print(f"This is x from what next function: {x}")
                conn.close()
                sys.exit()
            case _:
                print("Number out fo range.")
                mainFunc()
    except ValueError:
        print("Wrong! Enter only number.")

And i call it in this form:

what_next(mark_as_done, delete_task, conn, "Mark as done", "Delete task")

CodePudding user response:

what_next(mark_as_done(conn), delete_task(conn), conn, "Mark as done", "Delete task")

This is a function call, you acturally pass the return value of delete_task(conn) to what_next. If you what to pass a function itself, just use its name only, like this:

what_next(mark_as_done, delete_task, conn, "Mark as done", "Delete task")

Then you can call these function in what_next. But indeed you can pack the conn with functions together, which is called "function closure":

what_next(lambda : mark_as_done(conn), lambda : delete_task(conn), conn, "Mark as done", "Delete task")
  • Related