Skip to content

Instantly share code, notes, and snippets.

@alexandre
Created June 26, 2014 19:23
Show Gist options
  • Save alexandre/fecb9501e8dae05f3634 to your computer and use it in GitHub Desktop.
Save alexandre/fecb9501e8dae05f3634 to your computer and use it in GitHub Desktop.
pretty print para testes no terminal python.
'''
Para testar um comando, função, whatever...é bem comum utilizarmos o terminal
do python. E para melhorar o retorno ao consultar uma lista, tupla, dicionário e etc, existe
o pprint.
Situação: Eu ainda não conheço bem os atributos de uma classe e nessa situação, eu gosto de usar a função dir().
Abaixo o resultado no terminal com e sem o pprint
'''
>>> foo = dict()
>>> dir(foo)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> from pprint import pprint
>>> pprint(dir(foo))
['__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'clear',
'copy',
'fromkeys',
'get',
'items',
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
>>>
'''
Isso é bem simples, mas bem útil para quando temos uma classe com muitos atributos...
IMHO, uma boa visualização colabora bastante...
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment