python 标准库记录

获取函数的调用堆栈信息

frame = sys._getframe([depth])

  • 可获取到函数名, 函数行号, 调用堆栈, 函数参数等信息
  • 实际工作中: 在获取异常信息,或者需要堆栈信息时都会用到
    """
    Return a frame object from the call stack.
    If optional integer depth is given, return the frame object that many calls below the top of the stack.
    If that is deeper than the call stack, ValueError is raised.
    The default for depth is zero, returning the frame at the top of the call stack.
    """
    参考: sys模块的相关函数

inspect 模块提供对实时对象及其源代码进行内省的函数

可获取堆栈信息, 可获取源代码, 有很多类型判断

  • 很多类型检查函数, 模块, frame, 函数, 方法, 等类型检查
  • 获取源代码
  • 获取类或者函数的参数信息, (获取函数参数时要注意函数是否被装饰器装饰, 要进行unwrap)
  • 解析堆栈信息
  • 实际工作中应用: 获取装饰器装饰函数绑定的所有参数,以及inspect提供的类型检查
    eg:

inspect.getcallargs(func[,*args][, **kwargs]): 将args和kwargs参数分别绑定到对应的位置参数和关键字参数上,并以字典形式返回

参考: Python3标准库

posted @ 2019-12-25 14:29  JonPan  阅读(157)  评论(0)    收藏  举报