Home > database >  How do I detect in python if the type of return value if it is an Error
How do I detect in python if the type of return value if it is an Error

Time:11-17

I have a function which either returns a dataframe or an Exception.

def func():
   try:
       # try creating a dataframe df
       return df
   except BaseException as error:
       return error

def func2():
   return_value = func()
   if return_value is an exception:
      # do this
   else:
      # do that

Another function calls it and I want to know if the return object is a dataframe or an exception.

How do I do that?

Thanks in advance

CodePudding user response:

Without knowing the context of what you want to accomplish, you can use isinstance(return_value, Exception). It should do what you are after.

CodePudding user response:

Can't you take an approach like this:

def func():
    try:
       # try creating a dataframe df
        return True, df
    except BaseException as error:
        return False, error

def func2():
    success, return_value = func()
    if not success:
        # do this
    else:
        # do that

CodePudding user response:

This should help. Return df or None and easy to check the return value.

from contextlib import suppress

def func():
    with suppress(BaseException):
        # try creating a dataframe df
        return df

def func2():
    retval = func() # None or df
  • Related