diff --git a/mcproto/packets/packet_map.py b/mcproto/packets/packet_map.py index 56a274c9..91bc2e02 100644 --- a/mcproto/packets/packet_map.py +++ b/mcproto/packets/packet_map.py @@ -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 @@ -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])