Base
_base
¶
CacheEndpoint
¶
CacheStats
¶
Statistics tracking cache hits, misses, insertions, and evictions.
Attributes:
| Name | Type | Description |
|---|---|---|
hits |
int
|
Number of successful cache lookups. |
misses |
int
|
Number of failed cache lookups. |
sets |
int
|
Number of entries inserted or updated in the cache. |
evictions |
int
|
Number of entries removed due to reaching maximum cache capacity (LRU eviction). |
Examples:
stats = client.cache.stats
print(f"Hits: {stats.hits}, Misses: {stats.misses}")
print(f"Hit Ratio: {stats.hit_ratio:.1%}")
reset
¶
Resets all statistical counters to zero.
Examples:
BaseCacheState
¶
BaseCacheState(
max_size: int = 100,
model: type[BaseModel] | None = None,
name: str = "",
endpoint_key_is_id: bool = False,
url_suffix: str = "",
is_list: bool = False,
)
Bases: MutableMapping[_KT, _VT], Generic[_KT, _VT, _ClientT]
In-memory LRU cache state with endpoint indexing and lookup metrics.
Manages cached items in an OrderedDict respecting a maximum capacity,
tracks endpoint URLs by name and ID, and records lookup statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_size
|
int
|
Maximum number of items to keep in memory before evicting least recently used items. |
100
|
model
|
type[BaseModel] | None
|
The PokeLance model class to instantiate when deserializing payloads. |
None
|
name
|
str
|
The name of this cache partition (e.g. 'pokemon', 'berry'). |
''
|
endpoint_key_is_id
|
bool
|
Whether the primary key for endpoints in this cache is the numeric ID rather than the name. |
False
|
url_suffix
|
str
|
URL suffix to append when building endpoint URLs (e.g. '/encounters'). |
""
|
is_list
|
bool
|
Whether this cache stores lists of models rather than single model instances. |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
stats |
CacheStats
|
Real-time statistics for lookups, hits, misses, and evictions on this cache. |
endpoints |
dict[str, CacheEndpoint]
|
Mapping from resource name (or ID) to CacheEndpoint metadata. |
identifiers |
set[str]
|
Set of all valid resource names and IDs known to this cache. |
cache |
OrderedDict[_KT, _VT]
|
The underlying OrderedDict storing cached items. |
Source code in pokelance/cache/_base.py
def __init__(
self,
max_size: int = 100,
model: type[BaseModel] | None = None,
name: str = "",
endpoint_key_is_id: bool = False,
url_suffix: str = "",
is_list: bool = False,
) -> None:
self._max_size = max_size
self._model = model
self._name = name or self.__class__.__name__
self._endpoint_key_is_id = endpoint_key_is_id
self._url_suffix = url_suffix
self._is_list = is_list
self._cache: OrderedDict[_KT, _VT] = OrderedDict()
self._endpoints: dict[str, CacheEndpoint] = {}
self._endpoints_by_id: dict[str, str] = {}
self._identifiers: set[str] = set()
self._endpoints_cached: bool = False
self._stats: CacheStats = CacheStats()
endpoints
property
¶
endpoints: dict[str, CacheEndpoint]
Mapping from resource name (or ID) to CacheEndpoint metadata.
identifiers
property
¶
Every valid resource name and ID known to this cache partition.
from_payload
¶
Creates a model instance or list of model instances from a raw payload dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any] | list[dict[str, Any]]
|
The raw JSON payload from PokéAPI. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | list[BaseModel]
|
The instantiated PokeLance model or list of models. |
Source code in pokelance/cache/_base.py
def from_payload(self, payload: dict[str, t.Any] | list[dict[str, t.Any]]) -> _VT:
"""Creates a model instance or list of model instances from a raw payload dict.
Parameters
----------
payload : dict[str, t.Any] | list[dict[str, t.Any]]
The raw JSON payload from PokéAPI.
Returns
-------
BaseModel | list[BaseModel]
The instantiated PokeLance model or list of models.
"""
if self._model is None:
raise RuntimeError(f"Model class not configured for cache '{self._name}'")
if isinstance(payload, list):
return t.cast("_VT", [self._model.from_payload(item) for item in payload])
return t.cast("_VT", self._model.from_payload(payload))
setdefault
¶
Returns the cached value for key if present, otherwise inserts default and returns it.
Source code in pokelance/cache/_base.py
@override
def setdefault(self, __key: _KT, /, __default: _VT | None = None) -> _VT:
"""Returns the cached value for key if present, otherwise inserts default and returns it."""
if __key not in self._cache and __default is not None:
self[__key] = __default
return self._cache[__key]
self._stats.hits += 1
self._cache.move_to_end(__key)
return self._cache[__key]
clear
¶
Clears all cached model data while keeping the endpoint registry intact.
Examples:
set_ready
¶
reset_endpoints
¶
Clears the endpoint registry and marks the cache as unready.
get
¶
Gets an item from the cache. If the exact key is missing, attempts alias resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Route
|
The endpoint route to look up. |
required |
default
|
BaseModel | list[BaseModel] | None
|
The default value returned if not found in cache. |
None
|
Returns:
| Type | Description |
|---|---|
BaseModel | list[BaseModel] | None
|
The cached model instance or default if not cached. |
Examples:
from pokelance.endpoints import Endpoint
route = Endpoint.get_pokemon("pikachu")
cached_pokemon = client.cache.pokemon.pokemon.get(route)
Source code in pokelance/cache/_base.py
@override
def get(self, key: _KT, default: _VT | None = None) -> _VT | None: # ty: ignore[invalid-method-override] # pyright: ignore[reportIncompatibleMethodOverride]
"""Gets an item from the cache. If the exact key is missing, attempts alias resolution.
Parameters
----------
key : Route
The endpoint route to look up.
default : BaseModel | list[BaseModel] | None, optional
The default value returned if not found in cache.
Returns
-------
BaseModel | list[BaseModel] | None
The cached model instance or default if not cached.
Examples
--------
```python
from pokelance.endpoints import Endpoint
route = Endpoint.get_pokemon("pikachu")
cached_pokemon = client.cache.pokemon.pokemon.get(route)
```
"""
if key in self._cache:
self._stats.hits += 1
self._cache.move_to_end(key)
return self._cache[key]
requested = key.endpoint.split("/")[-1]
alias = self._endpoints_by_id.get(requested) or self._endpoints.get(requested)
if alias:
for k, v in self.items():
if k.endpoint.split("/")[-1] == str(alias):
self._stats.hits += 1
self._cache.move_to_end(k)
return v
self._stats.misses += 1
return default
load_documents
¶
Loads endpoint metadata documents into this cache partition's registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[dict[str, str]]
|
The raw list of endpoint documents containing |
required |
Source code in pokelance/cache/_base.py
def load_documents(self, data: list[dict[str, str]]) -> None:
"""Loads endpoint metadata documents into this cache partition's registry.
Parameters
----------
data : list[dict[str, str]]
The raw list of endpoint documents containing `name` and `url`.
"""
self.reset_endpoints()
for document in data:
original_url = document["url"]
id_ = int(original_url.split("/")[-2])
key = str(id_) if self._endpoint_key_is_id else document["name"]
url = f"{original_url.strip('/')}{self._url_suffix}" if self._url_suffix else original_url
self._endpoints[key] = CacheEndpoint(url=url, id=id_)
self._endpoints_by_id[str(id_)] = key
self._mark_endpoints_cached()
set_size
¶
set_size(size: int) -> None
Sets the maximum capacity of this cache partition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
The maximum number of items allowed in the cache. |
required |
Examples:
Source code in pokelance/cache/_base.py
serialize
¶
Serializes all in-memory cached models into a raw dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary mapping endpoint routes to raw model payload dictionaries. |
Examples:
Source code in pokelance/cache/_base.py
def serialize(self) -> dict[str, t.Any]:
"""Serializes all in-memory cached models into a raw dictionary.
Returns
-------
dict[str, t.Any]
A dictionary mapping endpoint routes to raw model payload dictionaries.
Examples
--------
```python
data = client.cache.pokemon.pokemon.serialize()
```
"""
dummy: dict[str, t.Any] = {}
for k, v in self.items():
dummy[k.endpoint] = v.raw if isinstance(v, BaseModel) else [i.raw for i in v]
return dummy
deserialize
¶
Populates this cache partition from a serialized dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary previously generated by |
required |
Examples:
Source code in pokelance/cache/_base.py
def deserialize(self, data: dict[str, t.Any]) -> None:
"""Populates this cache partition from a serialized dictionary.
Parameters
----------
data : dict[str, t.Any]
Dictionary previously generated by `serialize()`.
Examples
--------
```python
client.cache.pokemon.pokemon.deserialize(saved_data)
```
"""
self._max_size = max(self._max_size, len(data))
for endpoint, info in data.items():
route = Route(endpoint=endpoint)
self.setdefault(t.cast("_KT", route), self.from_payload(info))
BaseCacheGroup
¶
Bases: Generic[_ClientT, _CacheT]
Base class for all category cache aggregates.
Groups multiple related sub-caches (e.g. berry, berry_firmness, berry_flavor)
under a unified namespace and provides batch management methods.
Attributes:
| Name | Type | Description |
|---|---|---|
max_size |
int
|
Maximum cache capacity configured across sub-caches in this group. |
stats
property
¶
stats: CacheStats
set_client
¶
Sets the parent client instance for all sub-caches in this group.
set_size
¶
set_size(max_size: int = 100) -> None
Sets the maximum cache capacity for all sub-caches in this group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_size
|
int
|
The maximum number of items allowed in each sub-cache. |
100
|
Examples:
Source code in pokelance/cache/_base.py
def set_size(self, max_size: int = 100) -> None:
"""Sets the maximum cache capacity for all sub-caches in this group.
Parameters
----------
max_size : int, default: 100
The maximum number of items allowed in each sub-cache.
Examples
--------
```python
client.cache.pokemon.set_size(250)
```
"""
self.max_size = max_size
for cache in self._walk_caches():
cache.set_size(max_size)
clear
¶
Clears all cached model data in every sub-cache in this group.
Examples:
reset
¶
BaseCacheManager
¶
Bases: Generic[_ClientT, _GroupT]
Base manager coordinating all category cache groups across the client.
Provides global configuration, bulk endpoint loading, cache clearance, and cumulative statistics across all sub-caches.
Attributes:
| Name | Type | Description |
|---|---|---|
client |
ClientBase
|
The parent client instance owning this cache manager. |
max_size |
int, default: 100
|
The default maximum capacity applied to all sub-caches. |
stats
property
¶
stats: CacheStats
set_size
¶
set_size(max_size: int = 100) -> None
Sets the maximum cache size across all category aggregates and sub-caches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_size
|
int
|
The maximum number of items allowed in each cache partition. |
100
|
Examples:
Source code in pokelance/cache/_base.py
def set_size(self, max_size: int = 100) -> None:
"""Sets the maximum cache size across all category aggregates and sub-caches.
Parameters
----------
max_size : int, default: 100
The maximum number of items allowed in each cache partition.
Examples
--------
```python
client.cache.set_size(500)
```
"""
self.max_size = max_size
for aggregate in self._walk_aggregates():
aggregate.set_size(max_size)
load_documents
¶
Loads endpoint metadata documents into the specified category sub-cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
The top-level category name (e.g. 'pokemon', 'berry'). |
required |
_type
|
str
|
The specific sub-cache partition name (e.g. 'pokemon_species', 'berry_flavor'). |
required |
data
|
list[dict[str, str]]
|
The raw list of endpoint documents. |
required |
Source code in pokelance/cache/_base.py
def load_documents(self, category: str, _type: str, data: list[dict[str, str]]) -> None:
"""Loads endpoint metadata documents into the specified category sub-cache.
Parameters
----------
category : str
The top-level category name (e.g. 'pokemon', 'berry').
_type : str
The specific sub-cache partition name (e.g. 'pokemon_species', 'berry_flavor').
data : list[dict[str, str]]
The raw list of endpoint documents.
"""
getattr(getattr(self, category.lower()), _type).load_documents(data)
clear
¶
Clears all cached model data across all category aggregates.
Examples:
reset
¶
Resets all endpoint registries across all category aggregates.
Examples: