You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何判断函数返回值是Exception异常对象还是DataFrame

判断返回对象类型的实现方法

核心思路是使用Python内置的isinstance()函数判断对象的继承关系,即可准确区分异常对象和DataFrame对象。

具体实现代码

import pandas as pd

def func():
   try:
       # 模拟创建DataFrame的逻辑
       df = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]})
       return df
   except BaseException as error:
       return error

def func2():
   return_value = func()
   if isinstance(return_value, BaseException):
      # 异常分支逻辑
      print(f"执行出错,错误信息:{return_value}")
   elif isinstance(return_value, pd.DataFrame):
      # 正常DataFrame处理逻辑
      print(f"执行成功,DataFrame行数:{return_value.shape[0]}")
   else:
      # 可选:兜底其他未知返回类型的逻辑
      print("返回值类型不符合预期")

注意事项

  • 如果你能保证func只会返回异常和DataFrame两种类型,可以省略DataFrame的类型判断,直接走else分支即可
  • 优先使用isinstance()而非type()做类型判断:isinstance()支持子类继承的识别,兼容性更强,比如后续自定义了继承DataFrame的子类也能正确识别
  • 只要你返回的异常类是Python标准异常或者继承自BaseException的自定义异常,都可以通过上述判断逻辑正确识别

内容的提问来源于stack exchange,提问作者KawaiKx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:06:02