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