refactor: add __slots__ to class definitions to save memory (#12)

* refactor: add __slots__ to class definitions to save memory

* Update revolt/channel.py

Co-authored-by: Zomatree <39768508+Zomatree@users.noreply.github.com>

* Update revolt/client.py

Co-authored-by: Zomatree <39768508+Zomatree@users.noreply.github.com>

* revert changes

Co-authored-by: Zomatree <39768508+Zomatree@users.noreply.github.com>
This commit is contained in:
null
2021-09-04 22:33:05 +07:00
committed by GitHub
parent a55ab98877
commit e3bb82c71f
13 changed files with 39 additions and 12 deletions
+2 -1
View File
@@ -36,6 +36,8 @@ class Asset:
type: :class:`AssetType`
The type of asset it is
"""
__slots__ = ("state", "id", "tag", "size", "filename", "content_type", "width", "height", "type")
def __init__(self, data: FilePayload, state: State):
self.state = state
@@ -54,7 +56,6 @@ class Asset:
self.width = None
self.content_type = data["content_type"]
self.type = AssetType(metadata["type"])
async def read(self) -> bytes:
+7 -1
View File
@@ -29,6 +29,8 @@ class Channel:
server: Optional[:class:`Server`]
The server the channel is part of
"""
__slots__ = ("state", "id", "channel_type", "server")
def __init__(self, data: ChannelPayload, state: State):
self.state = state
self.id = data["_id"]
@@ -46,6 +48,8 @@ class DMChannel(Channel, Messageable):
super().__init__(data, state)
class GroupDMChannel(Channel, Messageable):
__slots__ = ("recipients", "name", "owner")
"""A group DM channel"""
def __init__(self, data: GroupDMChannelPayload, state: State):
super().__init__(data, state)
@@ -54,6 +58,8 @@ class GroupDMChannel(Channel, Messageable):
self.owner = state.get_user(data["owner"])
class TextChannel(Channel, Messageable):
__slots__ = ("name", "description", "last_message", "last_message_id")
"""A text channel"""
def __init__(self, data: TextChannelPayload, state: State):
super().__init__(data, state)
@@ -84,4 +90,4 @@ def channel_factory(data: ChannelPayload, state: State) -> Channel:
elif data["channel_type"] == "VoiceChannel":
return VoiceChannel(data, state)
else:
raise Exception
raise Exception
+2
View File
@@ -40,6 +40,8 @@ class Client:
max_messages: :class:`int`
The max amount of messages stored in the cache, by default this is 5k
"""
__slots__ = ("session", "token", "api_url", "max_messages", "api_info", "http", "state", "websocket", "listeners")
def __init__(self, session: aiohttp.ClientSession, token: str, api_url: str = "https://api.revolt.chat", max_messages: int = 5000):
self.session = session
self.token = token
+4 -5
View File
@@ -16,6 +16,8 @@ class File:
spoiler: bool
Determines if the file will be a spoiler, this prefexes the filename with `SPOILER_`
"""
__slots__ = ("f", "spoiler", "filename")
def __init__(self, file: Union[str, bytes], *, filename: Optional[str] = None, spoiler: bool = False):
if isinstance(file, str):
self.f = open(file, "rb")
@@ -25,12 +27,9 @@ class File:
if filename is None and isinstance(file, str):
filename = self.f.name
if spoiler or (filename and filename.startswith("SPOILER_")):
self.spoiler = True
else:
self.spoiler = False
self.spoiler = spoiler or (filename and filename.startswith("SPOILER_"))
if self.spoiler and (filename and not filename.startswith("SPOILER_")):
filename = f"SPOILER_{filename}"
self.filename = filename
self.filename = filename
+2
View File
@@ -36,6 +36,8 @@ T = TypeVar("T")
Request = Coroutine[Any, Any, T]
class HttpClient:
__slots__ = ("session", "token", "api_url", "api_info")
def __init__(self, session: aiohttp.ClientSession, token: str, api_url: str, api_info: ApiInfo):
self.session = session
self.token = token
+2
View File
@@ -28,6 +28,8 @@ class Member(User):
server: :class:`Server`
The server the member belongs to
"""
__slots__ = ("_state", "nickname", "roles", "server")
def __init__(self, data: MemberPayload, server: Server, state: State):
user = state.get_user(data["_id"]["user"])
assert user
+2
View File
@@ -33,6 +33,8 @@ class Message:
author: Union[:class:`Member`, :class:`User`]
The author of the message, will be :class:`User` in DMs
"""
__slots__ = ("state", "id", "content", "attachments", "embeds", "channel", "server", "author")
def __init__(self, data: MessagePayload, state: State):
self.state = state
+3 -1
View File
@@ -20,6 +20,8 @@ class Messageable:
The id of the channel
"""
id: str
__slots__ = ("state", "id")
def __init__(self, state: State):
self.state = state
@@ -47,4 +49,4 @@ class Messageable:
embed_payload = [embed.to_dict() for embed in embeds] if embeds else None
message = await self.state.http.send_message(self.id, content, embed_payload, attachments)
return self.state.add_message(message)
return self.state.add_message(message)
+6
View File
@@ -25,9 +25,15 @@ class Role:
rank: :class:`int`
The position of the role in the role heirarchy
"""
__slots__ = ("id", "name", "colour", "hoist", "rank")
def __init__(self, data: RolePayload, role_id: str, state: State):
self.id = role_id
self.name = data["name"]
self.colour = data.get("colour")
self.hoist = data.get("hoist", False)
self.rank = data.get("rank", 0)
@property
def color(self):
return self.colour
+2
View File
@@ -26,6 +26,8 @@ class Server:
owner: Optional[:class:`Member`]
The owner of the server
"""
__slots__ = ("state", "id", "name", "owner", "default_permissions", "_members", "_roles", "_channels")
def __init__(self, data: ServerPayload, state: State):
self.state = state
self.id = data["_id"]
+4 -4
View File
@@ -22,6 +22,8 @@ if TYPE_CHECKING:
__all__ = ("State",)
class State:
__slots__ = ("http", "api_info", "max_messages", "users", "channels", "servers", "messages")
def __init__(self, http: HttpClient, api_info: ApiInfo, max_messages: int):
self.http = http
self.api_info = api_info
@@ -38,10 +40,8 @@ class State:
def get_member(self, server_id: str, member_id: str) -> Optional[Member]:
server = self.servers.get(server_id)
if not server:
return
return server.get_member(member_id)
if server:
return server.get_member(member_id)
def get_channel(self, id: str) -> Optional[Channel]:
return self.channels.get(id)
+1
View File
@@ -52,6 +52,7 @@ class User:
The users status
"""
__flattern_attributes__ = ("id", "name", "bot", "owner", "badges", "online", "flags", "avatar", "relations", "relationship", "status")
__slots__ = (*__flattern_attributes__, "state")
def __init__(self, data: UserPayload, state: State):
self.state = state
+2
View File
@@ -31,6 +31,8 @@ __all__ = ("WebsocketHandler",)
logger = logging.getLogger("revolt")
class WebsocketHandler:
__slots__ = ("session", "token", "ws_url", "dispatch", "state", "websocket", "loop")
def __init__(self, session: aiohttp.ClientSession, token: str, ws_url: str, dispatch: Callable[..., None], state: State):
self.session = session
self.token = token