Home  >  Article  >  Backend Development  >  python中实现php的var_dump函数功能

python中实现php的var_dump函数功能

WBOY
WBOYOriginal
2016-06-10 15:18:141305browse

最近在做python的web开发(原谅我的多变,好东西总想都学着。。。node.js也是),不过过程中总遇到些问题,不管是web.py还是django,开发起来确实没用php方便,毕竟存在的时间比较短,很多不完善的地方。

比如我在调试php中最常用的函数,var_dump,在python里找不到合适的替代函数。php中var_dump是一个特别有用的函数,它可以输出任何变量的值,不管你是一个对象还是一个数组,或者只是一个数。它总能用友好的方式输出,我调试的时候经常会需要看某位置的变量信息,调用它就很方便:

但是开发python的时候就没有太好的替代方案。

之前想到repr,但这个函数只是调用了对象中的__str__,和直接print obj没啥区别。print是打印它,而repr是将其作为值返回。如果对象所属的类没有定义__str__这个函数,那么返回的就会是难看的一串字符。

后来又想到了vars 函数,vars函数是python的内建函数,专门用来输出一个对象的内部信息。但这个对象所属的类中必须有__dict__函数。一般的类都有这个dict,但像[]和{}等对象就不存在这个dict,这样调用vars函数就会抛出一个异常:

复制代码 代码如下:

Traceback (most recent call last):
  File "", line 1, in
TypeError: vars() argument must have __dict__ attribute

所以后来几经寻找,找到一个个比较好,功能能够与var_dump类似的函数如下:

复制代码 代码如下:

def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj

这是使用方式:

复制代码 代码如下:

 class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'

from pprint import pprint
pprint(dump(obj))

最后输出是:

复制代码 代码如下:

{'__type__': '<__main__.stdclass object at>',
 'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
 'int': 1,
 'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
 'subObj': {'__type__': '<__main__.stdclass object at>',
            'value': 'foobar'},
 'tup': (1, 2, 3, 4)}   

然后github有个开源的module,可以参考:https://github.com/sha256/python-var-dump

说一下pprint这个函数,他是一个人性化输出的函数,会将要输出的内容用程序员喜欢的方式输出在屏幕上。参阅这篇文章比较好理解:http://www.jb51.net/article/60143.htm

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn