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" QUALNAME = "Base"
@staticmethod @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) return Object.all[int.from_bytes(b.read(4), "little")].read(b, *args)
def write(self, *args) -> bytes: def write(self, *args) -> bytes:
pass 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 __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) 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: def __len__(self) -> int:
return len(self.write()) return len(self.write())
def __getitem__(self, item): def __getitem__(self, item):
return getattr(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__( def __init__(
self, self,
*, *,
client: "pyrogram.client.ext.BaseClient", client: "pyrogram.BaseClient" = None,
id: str, id: str,
from_user: User, from_user: User,
query: str, query: str,
@ -62,7 +62,6 @@ class InlineQuery(PyrogramType, Update):
): ):
super().__init__(client) super().__init__(client)
self._client = client
self.id = id self.id = id
self.from_user = from_user self.from_user = from_user
self.query = query self.query = query

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -30,14 +30,17 @@ class PollOption(PyrogramType):
voter_count (``int``): voter_count (``int``):
Number of users that voted for this option. Number of users that voted for this option.
Equals to 0 until you vote. 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__( def __init__(
self, self,
*, *,
client: "pyrogram.client.ext.BaseClient", client: "pyrogram.BaseClient" = None,
text: str, text: str,
voter_count: int, voter_count: int,
data: bytes data: bytes
@ -46,4 +49,4 @@ class PollOption(PyrogramType):
self.text = text self.text = text
self.voter_count = voter_count self.voter_count = voter_count
self._data = data # Hidden self.data = data

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -25,34 +25,45 @@ import pyrogram
class PyrogramType: class PyrogramType:
__slots__ = ["_client"] __slots__ = ["_client"]
def __init__(self, client: "pyrogram.client.ext.BaseClient"): def __init__(self, client: "pyrogram.BaseClient" = None):
self._client = client 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) 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): def __getitem__(self, item):
return getattr(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__( def __init__(
self, self,
*, *,
client: "pyrogram.client.ext.BaseClient", client: "pyrogram.BaseClient" = None,
id: int, id: int,
type: str, type: str,
title: str = None, title: str = None,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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