Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Python: Passing function name to another function, then using it in a try/catch

Options
  • 06-01-2022 11:33am
    #1
    Registered Users Posts: 5,575 ✭✭✭


    I'm trying to pass a function name to another function. So in the second function i say "Calling function {func.name} and then run a try on the function


    e.g


    try_function(function_name, 123)



    def try_function(function_name, *args):

    log.info(f"Running function {function_name.__name__})

    try:

    function_name(*args)

    except Exception as e:

    log.warning("Didnt work")



    The logging actually does the function and returns my values. I obviously dont want it to do it there


    How do i get it to print the name and then only execute in the try block



Comments

  • Registered Users Posts: 6,171 ✭✭✭Talisman


    I'm not sure what you are expecting to happen differently. The Try and Except block works as expected.

    try:
       # This code block can generate errors when executed
    
    except <error type>:
       # This code block is executed 
       # if the try block throws an error
    
    else:
       # This code block is executed only
       # if the try block executes successfully without errors
    
    finally:
       # This code block is always executed
    

    The code in the Try block is always executed to the point that an error occurs. If no error occurs then the Except block is not executed. The Else and Finally blocks are optional.

    To demonstrate using your code:

    import logging
    
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    
    def try_function(function_name, *args):
       logging.info(f"Running function '{function_name.__name__}'")
       try:
           function_name(*args)
       except Exception as e:
           logging.warning("Didn't work")
    
    # state variable
    state = False
    
    def upper_text(text):
       """ Returns upper case text. """
       return text.upper()
    
    def lower_text(text):
       """ Returns lower case text. """
       return text.lower()
    
    def text_func(func):
       """ Prints formatted text string if state is True otherwise raises an exception. """
       if state:
           result = func("Hello world!")
           print(result)
       else:
           warning_message = "'state' not set to True."
           logging.warning(warning_message)
           raise Exception(warning_message)
    

    In the piece of code the value of the 'state' variable determines whether or not 'text_func' prints a string value or raises an exception.

    # state is False
    try_function(text_func, upper_text)
    
    # Log:
    INFO:root:Running function 'text_func'
    WARNING:root:'state' not set to True.
    WARNING:root:Didn't work
    

    In this case there is no output from 'text_func' because its internal logic doesn't generate any in the event that 'state' is not True, but the code within the function is executed. When 'state' is True the "hello world!" string is printed.

    state = True
    # state is True
    try_function(text_func, lower_text)
    
    # Log:
    INFO:root:Running function 'text_func'
    
    # Output:
    hello world!
    

    Here's a simpler example:

    def division(numerator, divisor):
       print(numerator / divisor)
    
    try_function(division, 1, 2)
    
    Log output:
    INFO:root:Running function 'division'
    
    Result:
    0.5
    
    try_function(division, 1, 0)
    
    Log output:
    INFO:root:Running function 'division'
    WARNING:root:Didn't work
    

    The ZeroDivisionError is swallowed by the Except block of the try_function and the warning is logged.



Advertisement