【问题标题】:How to check if a return object is a dictionary in python [duplicate]如何检查返回对象是否是python中的字典[重复]
【发布时间】:2021-12-26 07:48:05
【问题描述】:

我编写了一个函数 f(x),它要么返回字典,要么返回错误消息。

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

return_value = myfunc()

if return_value a dictionary:
    do this
else:
    do that 

我需要检测另一个调用 f(x) 的函数 f(y) 中的返回类型。

我该怎么做?

提前致谢

【问题讨论】:

  • 对此不太确定,但我想你可以在myfunc() 之外直接访问try ... catch,因为如果出错,该函数会将异常传递给调用者。
  • @j1-lee:异常不会传播到myfunc()之外。
  • 你不应该return一个异常实例。你应该让它升起来。这就是异常如何工作的要点。

标签: python dictionary


【解决方案1】:
isinstance(return_value, dict)

【讨论】:

    【解决方案2】:

    您可以按如下方式检查值的类型:

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

    有几种方法可以检查值的类型,请参阅:How to check if type of a variable is string?

    【讨论】:

      【解决方案3】:

      您的示例未遵循正常的最佳实践,但您可以执行以下操作:

      if type(return_value) is dict:
      

      或

      if isinstance(return_value, dict):
      

      【讨论】:

        【解决方案4】:

        另一种方法是返回一个跟踪是否存在错误的元组:

        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 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-04
          • 1970-01-01
          • 2017-03-02
          • 2021-04-11
          • 2013-10-15
          • 2014-10-03
          • 2021-07-17
          • 2013-03-28
          相关资源
          最近更新 更多