Skip to content

Commit

Permalink
Add a new .stringify() function to visualize TLObjects more easily
Browse files Browse the repository at this point in the history
  • Loading branch information
Lonami committed Jul 4, 2017
1 parent 632fcb7 commit 8fd0d7e
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 2 deletions.
72 changes: 72 additions & 0 deletions telethon/tl/mtproto_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,79 @@ def need_resend(self):
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

Expand Down
8 changes: 6 additions & 2 deletions telethon_generator/tl_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ def _write_source_code(tlobject, builder, depth, type_constructors):

# 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))

Expand Down Expand Up @@ -408,9 +409,12 @@ def _write_source_code(tlobject, builder, depth, type_constructors):
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):
Expand Down

2 comments on commit 8fd0d7e

@udf
Copy link
Contributor

@udf udf commented on 8fd0d7e Jul 4, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! I don't know how anyone could get anything done without this.

@Lonami
Copy link
Member Author

@Lonami Lonami commented on 8fd0d7e Jul 4, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how anyone could get anything done

They didn't. It's Telegram what we're talking about :)

Please sign in to comment.