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,
read_types=read_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}
"""
__slots__ = [{slots}]
ID = {object_id}
QUALNAME = "{qualname}"
def __init__(self{arguments}):
{fields}

View File

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