0

I have written a function f(x) that either returns a dictionary or an error message.

def myfunc():
    try:
       return dictionary
    except BaseException as e:
       return e

return_value = myfunc()

if return_value a dictionary:
    do this
else:
    do that 

I need to detect the type of return in another function f(y) which calls f(x).

How do I do that?

thanks in advance

3
  • 1
    Not pretty sure about this, but I guess you can just to try ... catch outside myfunc(), since on error the function will pass the exception to the caller. Commented Nov 15, 2021 at 2:01
  • @j1-lee: The exception is not propagated outside of myfunc(). Commented Nov 15, 2021 at 2:02
  • You should not return an exception instance. You should just let it be raised. That's the point of how exceptions work. Commented Nov 15, 2021 at 2:21

4 Answers 4

4

Your example does not follow normal best practices, but you would do the following:

if type(return_value) is dict:

or

if isinstance(return_value, dict):
Sign up to request clarification or add additional context in comments.

Comments

2
isinstance(return_value, dict)

Comments

1

You can check a value's type as follows:

if type(return_value) == dict:
    print("It is a dictionary.")
else:
    pinrt("It is not a dictionary")

There are several ways to check a type of value, see: How to check if type of a variable is string?

Comments

0

An alternative is to return a tuple that keeps track of whether there was an error:

def myfunc():
    try:
       return (True, dictionary)
    except BaseException as e:
        return (False, e)

was_successful, return_value = myfunc()

if was_successful:
    do this
else:
    do that 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.