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

KawaiKx
  • 9,558
  • 19
  • 72
  • 111

4 Answers4

3

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):
Cresht
  • 1,020
  • 2
  • 6
  • 15
2
isinstance(return_value, dict)
ramwin
  • 5,803
  • 3
  • 27
  • 29
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?

Park
  • 2,446
  • 1
  • 16
  • 25
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 
Acccumulation
  • 3,491
  • 1
  • 8
  • 12