Python and Django I'm in the first month. Rails history is about 2 years. Why is Python's Debug so hard to see? Especially Model. The following display. Who would benefit from seeing this?
>>> class Foo(object):
pass
>>>
>>> repr(Foo())
'<__main__.Foo object at 0x02A74E50>'
If you look for the sea on the net and use repr, you can see it beautifully! Hooray! This frees you from the pain!
def __repr__(self):
return '<Stats: description={0.description!r}, mystat={0.mystat!r}>'.format(self)
... what's this annoying.
You need to write to each class. Is it possible to add a one-shot library or something? ?? I think.
Reference: http://stackoverflow.com/a/15929677/5114776
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
if __debug__:
# monkey-patch in useful repr() for all objects, but only in dev
def tablerepr(self):
return "<{}({})>".format(
self.__class__.__name__,
', '.join(
["{}={}".format(k, repr(self.__dict__[k]))
for k in sorted(self.__dict__.keys())
if k[0] != '_']
)
)
Base.__repr__ = tablerepr
>>> session.query(FooBar).get(1)
<FooBar(id=1, foo='bar', comments='foobar', hoge=1231242342341342342, fuga=datetime(2015, 5, 5, 5, 5, 5), tiger='waearsdtdygfyfguiohjohjohpp'>
However, it is still difficult to see with this reference alone. I'm not a machine! A format that is easy for people to see! Otherwise it's meaningless!
Base = declarative_base()
if __debug__:
# monkey-patch in useful repr() for all objects, but only in dev
def tab_char(max_length, target_lenght):
tab = []
tab_char_count = 4
tab_count = (max_length/tab_char_count - target_lenght/tab_char_count) + 1
for i in range(tab_count):
tab.append('\t')
return "".join(tab)
def table_repr(self):
max_length = max(map(lambda n: len(n), self.__dict__.keys()))
return "\n<{}({})>".format(
self.__class__.__name__,
', '.join(
["\n\t{}{}= {}".format(k, tab_char(max_length, len(k)), repr(self.__dict__[k]))
for k in sorted(self.__dict__.keys())
if k[0] != '_']
)
)
Base.__repr__ = table_repr
>>> session.query(FooBar).get(1)
<FooBar(
id = 1
fooooooooo = 'bar',
comments = 'foobar',
hoge = 1231242342341342342,
fuga = datetime(2015, 5, 5, 5, 5, 5),
tiger = 'waearsdtdygfyfguiohjohjohpp'>
Perfect.
Recommended Posts