Skip to content

Commit

Permalink
Cache packet map generation
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsDrike committed Jun 9, 2023
1 parent c58878e commit d15ee35
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions mcproto/packets/packet_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import importlib
import pkgutil
from collections.abc import Iterator, Mapping, Sequence
from functools import lru_cache
from types import ModuleType
from typing import Literal, NamedTuple, NoReturn, overload

Expand Down Expand Up @@ -93,12 +94,21 @@ def generate_packet_map(
...


@lru_cache()
def generate_packet_map(direction: PacketDirection, state: GameState) -> Mapping[int, type[Packet]]:
"""Dynamically generated a packet map for given ``direction`` and ``state``.
This generation is done by dynamically importing all of the modules containing these packets,
filtering them to only contain those pacekts with the specified parameters, and storing those
into a dictionary, using the packet id as key, and the packet class itself being the value.
As this fucntion is likely to be called quite often, and it uses dynamic importing to obtain
the packet classes, this function is cached, which means the logic only actually runs once,
after which, for the same arguments, the same dict will be returned.
..warning: As this function is cached, make sure to avoid modifying the returned dictionary,
as that will directly modify the stored version in the cache, leading to future calls
with the same arguments returning a wrong (modified) version of this dictionary.
"""
module = importlib.import_module(MODULE_PATHS[state])

Expand Down

0 comments on commit d15ee35

Please sign in to comment.