Add a new .stringify() function to visualize TLObjects more easily

This commit is contained in:
Lonami Exo 2017-07-04 21:15:47 +02:00
parent 632fcb7c00
commit 8fd0d7eadd
2 changed files with 78 additions and 2 deletions

View File

@ -30,7 +30,79 @@ class MTProtoRequest:
self.confirmed and not self.confirm_received and
datetime.now() - self.send_time > timedelta(seconds=3))
@staticmethod
def pretty_format(obj, indent=None):
"""Pretty formats the given object as a string which is returned.
If indent is None, a single line will be returned.
"""
if indent is None:
if isinstance(obj, MTProtoRequest):
return '{{{}: {}}}'.format(
type(obj).__name__,
MTProtoRequest.pretty_format(obj.to_dict())
)
if isinstance(obj, dict):
return '{{{}}}'.format(', '.join(
'{}: {}'.format(
k, MTProtoRequest.pretty_format(v)
) for k, v in obj.items()
))
elif isinstance(obj, str):
return '"{}"'.format(obj)
elif hasattr(obj, '__iter__'):
return '[{}]'.format(
', '.join(MTProtoRequest.pretty_format(x) for x in obj)
)
else:
return str(obj)
else:
result = []
if isinstance(obj, MTProtoRequest):
result.append('{')
result.append(type(obj).__name__)
result.append(': ')
result.append(MTProtoRequest.pretty_format(
obj.to_dict(), indent
))
elif isinstance(obj, dict):
result.append('{\n')
indent += 1
for k, v in obj.items():
result.append('\t' * indent)
result.append(k)
result.append(': ')
result.append(MTProtoRequest.pretty_format(v, indent))
result.append(',\n')
indent -= 1
result.append('\t' * indent)
result.append('}')
elif isinstance(obj, str):
result.append('"')
result.append(obj)
result.append('"')
elif hasattr(obj, '__iter__'):
result.append('[\n')
indent += 1
for x in obj:
result.append('\t' * indent)
result.append(MTProtoRequest.pretty_format(x, indent))
result.append(',\n')
indent -= 1
result.append('\t' * indent)
result.append(']')
else:
result.append(str(obj))
return ''.join(result)
# These should be overrode
def to_dict(self):
return {}
def on_send(self, writer):
pass

View File

@ -179,6 +179,7 @@ class TLGenerator:
# Both types and functions inherit from
# MTProtoRequest so they all can be sent
# TODO MTProtoRequest is not the best name for a type
builder.writeln('from {}.tl.mtproto_request import MTProtoRequest'
.format('.' * depth))
@ -408,9 +409,12 @@ class TLGenerator:
builder.end_block()
builder.writeln('def __str__(self):')
builder.writeln('return {}'.format(str(tlobject)))
# builder.end_block() # No need to end the last block
builder.writeln('return MTProtoRequest.pretty_format(self)')
builder.end_block()
builder.writeln('def stringify(self):')
builder.writeln('return MTProtoRequest.pretty_format(self, indent=0)')
# builder.end_block() # No need to end the last block
@staticmethod
def get_class_name(tlobject):