'How to avoid running argument function before the main function

I want to create a function that will react according to the success of the argument function and get the argument function's name.

Something like

def foo(argument_function):
    try:
        argument_function
        print(f"{somehow name of the argument_function} executed successfully.")
    except:
        print(f"{somehow name of the argument_function} failed.")
  1. argument_function should be executed only under the try statement. Otherwise, it will give an error and stop the script which I am trying to avoid.
  2. {somehow name of the argument_function} should return the name of the argument_function.

for successful attempt:

foo(print("Hello world!"))

should return

>>Hello world!
>>print("Hello world!") executed successfully.

for unsuccessful attempt:

foo(prnt("Hello world!"))

should return

>>prnt("Hello world!") failed.


Solution 1:[1]

import typing
def foo(argument_function:typing.Callable):
    try:
        argument_function()
        print(f"{argument_function.__name__} executed successfully.")
    except:
        print(f"{argument_function.__name__} failed.")
print(foo.__name__) # returns foo

Or use:

def foo(argument_function:callable):

__name__ returns function name and if you ensure the function is an object then adding () should run the function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1