最近在做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 "<stdin>", line 1, in <module>
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 0x2b126000b890>',
'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 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
然后github有個開源的module,可以參考:https://github.com/sha256/python-var-dump說一下pprint這個函數,他是一個人性化輸出的函數,會將要輸出的內容用程序員喜歡的方式輸出在屏幕上。參閱這篇文章比較好理解://m.survivalescaperooms.com/article/60143.htm