Use a better repr for all types

now eval(repr(obj) == obj
This commit is contained in:
Dan 2019-05-13 16:06:34 +02:00
parent 0e80b39c2c
commit 65c07b7d34
44 changed files with 119 additions and 98 deletions

View File

@ -30,43 +30,51 @@ class Object:
QUALNAME = "Base"
@staticmethod
def read(b: BytesIO, *args):
def read(b: BytesIO, *args): # TODO: Rename b -> data
return Object.all[int.from_bytes(b.read(4), "little")].read(b, *args)
def write(self, *args) -> bytes:
pass
def __eq__(self, other: "Object") -> bool:
for attr in self.__slots__:
try:
if getattr(self, attr) != getattr(other, attr):
return False
except AttributeError:
return False
return True
def __str__(self) -> str:
def default(obj: Object):
try:
return OrderedDict(
[("_", obj.QUALNAME)]
+ [(attr, getattr(obj, attr))
for attr in obj.__slots__
if getattr(obj, attr) is not None]
)
except AttributeError:
if isinstance(obj, datetime):
return obj.strftime("%d-%b-%Y %H:%M:%S")
else:
return repr(obj)
return dumps(self, indent=4, default=default, ensure_ascii=False)
def __repr__(self) -> str:
return "pyrogram.api.{}({})".format(
self.QUALNAME,
", ".join(
"{}={}".format(attr, repr(getattr(self, attr)))
for attr in self.__slots__
if getattr(self, attr) is not None
)
)
def __len__(self) -> int:
return len(self.write())
def __getitem__(self, item):
return getattr(self, item)
def remove_none(obj):
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none(x) for x in obj if x is not None)
elif isinstance(obj, dict):
return type(obj)((remove_none(k), remove_none(v)) for k, v in obj.items() if k is not None and v is not None)
else:
return obj
def default(o: "Object"):
try:
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)

View File

@ -53,7 +53,7 @@ class InlineQuery(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: str,
from_user: User,
query: str,
@ -62,7 +62,6 @@ class InlineQuery(PyrogramType, Update):
):
super().__init__(client)
self._client = client
self.id = id
self.from_user = from_user
self.query = query

View File

@ -50,7 +50,7 @@ class InlineQueryResult(PyrogramType):
__slots__ = ["type", "id"]
def __init__(self, type: str, id: str):
super().__init__(None)
super().__init__()
self.type = type
self.id = id

View File

@ -33,7 +33,7 @@ class InputMedia(PyrogramType):
__slots__ = ["media", "caption", "parse_mode"]
def __init__(self, media: str, caption: str, parse_mode: str):
super().__init__(None)
super().__init__()
self.media = media
self.caption = caption

View File

@ -34,4 +34,4 @@ class InputMessageContent(PyrogramType):
__slots__ = []
def __init__(self):
super().__init__(None)
super().__init__()

View File

@ -28,4 +28,4 @@ class CallbackGame(PyrogramType):
__slots__ = []
def __init__(self):
super().__init__(None)
super().__init__()

View File

@ -64,7 +64,7 @@ class CallbackQuery(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: str,
from_user: User,
chat_instance: str,

View File

@ -42,7 +42,7 @@ class ForceReply(PyrogramType):
self,
selective: bool = None
):
super().__init__(None)
super().__init__()
self.selective = selective

View File

@ -42,7 +42,7 @@ class GameHighScore(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
user: User,
score: int,
position: int = None

View File

@ -40,7 +40,7 @@ class GameHighScores(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
total_count: int,
game_high_scores: List[GameHighScore]
):

View File

@ -71,7 +71,7 @@ class InlineKeyboardButton(PyrogramType):
switch_inline_query_current_chat: str = None,
callback_game: CallbackGame = None
):
super().__init__(None)
super().__init__()
self.text = str(text)
self.url = url

View File

@ -37,7 +37,7 @@ class InlineKeyboardMarkup(PyrogramType):
self,
inline_keyboard: List[List[InlineKeyboardButton]]
):
super().__init__(None)
super().__init__()
self.inline_keyboard = inline_keyboard

View File

@ -48,7 +48,7 @@ class KeyboardButton(PyrogramType):
request_contact: bool = None,
request_location: bool = None
):
super().__init__(None)
super().__init__()
self.text = str(text)
self.request_contact = request_contact

View File

@ -58,7 +58,7 @@ class ReplyKeyboardMarkup(PyrogramType):
one_time_keyboard: bool = None,
selective: bool = None
):
super().__init__(None)
super().__init__()
self.keyboard = keyboard
self.resize_keyboard = resize_keyboard

View File

@ -43,7 +43,7 @@ class ReplyKeyboardRemove(PyrogramType):
self,
selective: bool = None
):
super().__init__(None)
super().__init__()
self.selective = selective

View File

@ -62,7 +62,7 @@ class Animation(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
width: int,
height: int,

View File

@ -62,7 +62,7 @@ class Audio(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
duration: int,
thumb: PhotoSize = None,

View File

@ -47,7 +47,7 @@ class Contact(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
phone_number: str,
first_name: str,
last_name: str = None,

View File

@ -53,7 +53,7 @@ class Document(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
thumb: PhotoSize = None,
file_name: str = None,

View File

@ -53,7 +53,7 @@ class Game(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: int,
title: str,
short_name: str,

View File

@ -38,7 +38,7 @@ class Location(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
longitude: float,
latitude: float
):

View File

@ -282,7 +282,7 @@ class Message(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
message_id: int,
date: int = None,
chat: Chat = None,
@ -2852,7 +2852,7 @@ class Message(PyrogramType, Update):
block: bool = True,
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
) -> str:
"""Bound method *download* of :obj:`Message`.
Use as a shortcut for:

View File

@ -68,7 +68,7 @@ class MessageEntity(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
type: str,
offset: int,
length: int,

View File

@ -42,7 +42,7 @@ class Messages(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
total_count: int,
messages: List[Message]
):

View File

@ -46,7 +46,7 @@ class Photo(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: str,
date: int,
sizes: List[PhotoSize]

View File

@ -47,7 +47,7 @@ class PhotoSize(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
width: int,
height: int,

View File

@ -53,7 +53,7 @@ class Poll(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: str,
question: str,
options: List[PollOption],

View File

@ -30,14 +30,17 @@ class PollOption(PyrogramType):
voter_count (``int``):
Number of users that voted for this option.
Equals to 0 until you vote.
data (``bytes``):
The data this poll option is holding.
"""
__slots__ = ["text", "voter_count", "_data"]
__slots__ = ["text", "voter_count", "data"]
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
text: str,
voter_count: int,
data: bytes
@ -46,4 +49,4 @@ class PollOption(PyrogramType):
self.text = text
self.voter_count = voter_count
self._data = data # Hidden
self.data = data

View File

@ -71,7 +71,7 @@ class Sticker(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
width: int,
height: int,

View File

@ -39,7 +39,7 @@ class UserProfilePhotos(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
total_count: int,
photos: List[Photo]
):

View File

@ -49,7 +49,7 @@ class Venue(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
location: Location,
title: str,
address: str,

View File

@ -68,7 +68,7 @@ class Video(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
width: int,
height: int,

View File

@ -56,7 +56,7 @@ class VideoNote(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
length: int,
duration: int,

View File

@ -52,7 +52,7 @@ class Voice(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
file_id: str,
duration: int,
waveform: bytes = None,

View File

@ -25,34 +25,45 @@ import pyrogram
class PyrogramType:
__slots__ = ["_client"]
def __init__(self, client: "pyrogram.client.ext.BaseClient"):
def __init__(self, client: "pyrogram.BaseClient" = None):
self._client = client
def __str__(self):
if self._client is None:
del self._client
def __eq__(self, other: "PyrogramType") -> bool:
for attr in self.__slots__:
try:
if getattr(self, attr) != getattr(other, attr):
return False
except AttributeError:
return False
return True
def __str__(self) -> str:
def default(obj: PyrogramType):
try:
return OrderedDict(
[("_", "pyrogram." + obj.__class__.__name__)]
+ [(attr, getattr(obj, attr))
for attr in obj.__slots__
if getattr(obj, attr) is not None]
)
except AttributeError:
return repr(obj)
return dumps(self, indent=4, default=default, ensure_ascii=False)
def __repr__(self) -> str:
return "pyrogram.{}({})".format(
self.__class__.__name__,
", ".join(
"{}={}".format(attr, repr(getattr(self, attr)))
for attr in self.__slots__
if getattr(self, attr) is not None
)
)
def __getitem__(self, item):
return getattr(self, item)
def remove_none(obj):
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none(x) for x in obj if x is not None)
elif isinstance(obj, dict):
return type(obj)((remove_none(k), remove_none(v)) for k, v in obj.items() if k is not None and v is not None)
else:
return obj
def default(o: PyrogramType):
try:
content = {i: getattr(o, i) for i in o.__slots__}
return remove_none(
OrderedDict(
[("_", "pyrogram." + o.__class__.__name__)]
+ [i for i in content.items() if not i[0].startswith("_")]
)
)
except AttributeError:
return repr(o)

View File

@ -89,7 +89,7 @@ class Chat(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: int,
type: str,
title: str = None,

View File

@ -59,7 +59,7 @@ class ChatMember(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
user: "pyrogram.User",
status: str,
date: int = None,

View File

@ -40,7 +40,7 @@ class ChatMembers(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
total_count: int,
chat_members: List[ChatMember]
):

View File

@ -40,7 +40,7 @@ class ChatPhoto(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
small_file_id: str,
big_file_id: str
):

View File

@ -50,7 +50,7 @@ class ChatPreview(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
title: str,
photo: ChatPhoto,
type: str,

View File

@ -51,7 +51,7 @@ class Dialog(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
chat: Chat,
top_message: "pyrogram.Message",
unread_messages_count: int,

View File

@ -41,7 +41,7 @@ class Dialogs(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
total_count: int,
dialogs: List[Dialog]
):

View File

@ -78,7 +78,7 @@ class User(PyrogramType):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
id: int,
is_self: bool,
is_contact: bool,

View File

@ -70,7 +70,7 @@ class UserStatus(PyrogramType, Update):
def __init__(
self,
*,
client: "pyrogram.client.ext.BaseClient",
client: "pyrogram.BaseClient" = None,
user_id: int,
online: bool = None,
offline: bool = None,