Add __slots__ to Telegram TL types

This commit is contained in:
Dan 2019-03-16 15:30:55 +01:00
parent c3470b2713
commit 6bd9ddc95e
3 changed files with 25 additions and 29 deletions

View File

@ -456,7 +456,9 @@ def start():
fields=fields, fields=fields,
read_types=read_types, read_types=read_types,
write_types=write_types, write_types=write_types,
return_arguments=", ".join([i[0] for i in sorted_args if i != ("flags", "#")]) return_arguments=", ".join([i[0] for i in sorted_args if i != ("flags", "#")]),
slots=", ".join(['"{}"'.format(i[0]) for i in sorted_args if i != ("flags", "#")]),
qualname="{}{}".format("{}.".format(c.namespace) if c.namespace else "", c.name)
) )
) )

View File

@ -9,7 +9,10 @@ class {class_name}(Object):
"""{docstring_args} """{docstring_args}
""" """
__slots__ = [{slots}]
ID = {object_id} ID = {object_id}
QUALNAME = "{qualname}"
def __init__(self{arguments}): def __init__(self{arguments}):
{fields} {fields}

View File

@ -19,14 +19,16 @@
from collections import OrderedDict from collections import OrderedDict
from datetime import datetime from datetime import datetime
from io import BytesIO from io import BytesIO
from json import JSONEncoder, dumps from json import dumps
from ..all import objects
class Object: class Object:
all = {} all = {}
__slots__ = []
QUALNAME = "Base"
@staticmethod @staticmethod
def read(b: BytesIO, *args): def read(b: BytesIO, *args):
return Object.all[int.from_bytes(b.read(4), "little")].read(b, *args) return Object.all[int.from_bytes(b.read(4), "little")].read(b, *args)
@ -35,7 +37,7 @@ class Object:
pass pass
def __str__(self) -> str: def __str__(self) -> str:
return dumps(self, cls=Encoder, indent=4) return dumps(self, indent=4, default=default)
def __bool__(self) -> bool: def __bool__(self) -> bool:
return True return True
@ -62,29 +64,18 @@ def remove_none(obj):
return obj return obj
class Encoder(JSONEncoder): def default(o: "Object"):
def default(self, o: Object): try:
try: content = {i: getattr(o, i) for i in o.__slots__}
content = o.__dict__
except AttributeError:
if isinstance(o, datetime):
return o.strftime("%d-%b-%Y %H:%M:%S")
else:
return repr(o)
name = o.__class__.__name__ return remove_none(
o = objects.get(getattr(o, "ID", None), None) OrderedDict(
[("_", o.QUALNAME)]
if o is not None: + [i for i in content.items()]
if o.startswith("pyrogram.client"): )
r = remove_none(OrderedDict([("_", "pyrogram:" + name)] + [i for i in content.items()])) )
r.pop("_client", None) except AttributeError:
if isinstance(o, datetime):
return r return o.strftime("%d-%b-%Y %H:%M:%S")
else:
return OrderedDict(
[("_", o.replace("pyrogram.api.types.", "telegram:"))]
+ [i for i in content.items()]
)
else: else:
return None return repr(o)