Skip to content

Commit f2e18fd

Browse files
committed
Refactor MetaPointer: Add Self return type for factory method, use ClassVar for _instances, simplify initialization, and enhance thread safety; add comprehensive test suite.
1 parent 678dbbc commit f2e18fd

File tree

2 files changed

+567
-10
lines changed

2 files changed

+567
-10
lines changed

src/lionweb/serialization/data/metapointer.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import threading
2-
from typing import Dict, Optional, Tuple
2+
from typing import ClassVar, Optional, Self
33

44
from lionweb.serialization.data.language_version import LanguageVersion
55

@@ -11,11 +11,14 @@ class MetaPointer:
1111
"""
1212

1313
# Class-level cache for interning instances
14-
_instances: Dict[Tuple[Optional[LanguageVersion], Optional[str]], "MetaPointer"] = (
15-
{}
16-
)
14+
_instances: ClassVar[
15+
dict[tuple[Optional[LanguageVersion], Optional[str]], "MetaPointer"]
16+
] = {}
1717
_lock = threading.Lock() # Thread-safe access to cache
1818

19+
_language_version: Optional[LanguageVersion]
20+
_key: Optional[str]
21+
1922
def __new__(
2023
cls,
2124
language_version: Optional[LanguageVersion] = None,
@@ -31,6 +34,8 @@ def __new__(
3134

3235
# Create new instance and cache it
3336
instance = super().__new__(cls)
37+
instance._language_version = language_version
38+
instance._key = key
3439
cls._instances[cache_key] = instance
3540
return instance
3641

@@ -39,18 +44,15 @@ def __init__(
3944
language_version: Optional[LanguageVersion] = None,
4045
key: Optional[str] = None,
4146
):
42-
# Only initialize if not already initialized (due to interning)
43-
if not hasattr(self, "_initialized"):
44-
self._language_version = language_version
45-
self._key = key
46-
self._initialized = True
47+
# no-op; kept for signature compatibility
48+
pass
4749

4850
@classmethod
4951
def of(
5052
cls,
5153
language_version: Optional[LanguageVersion] = None,
5254
key: Optional[str] = None,
53-
) -> "MetaPointer":
55+
) -> Self:
5456
"""
5557
Factory method to get an interned MetaPointer instance.
5658
This is the preferred way to create MetaPointer instances.

0 commit comments

Comments
 (0)