Skip to content

Commit 0487c9b

Browse files
committed
Used UserDict as base class for LazyFixtures
1 parent 4b19585 commit 0487c9b

File tree

1 file changed

+7
-24
lines changed

1 file changed

+7
-24
lines changed

src/dodal/device_manager.py

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22
import inspect
3-
import itertools
43
import typing
4+
from collections import UserDict
55
from collections.abc import Callable, Iterable, Mapping, MutableMapping
66
from functools import cached_property, wraps
77
from inspect import Parameter
@@ -47,44 +47,27 @@
4747
"""Sentinel value to distinguish between missing values and present but null values"""
4848

4949

50-
class LazyFixtures(Mapping[str, Any]):
50+
class LazyFixtures(UserDict[str, Any]):
5151
"""
5252
Wrapper around fixtures and fixture generators
5353
5454
If a fixture is provided at runtime, the generator function does not have to be called.
5555
"""
5656

57-
ready: MutableMapping[str, Any]
5857
lazy: MutableMapping[str, Callable[[], Any]]
5958

6059
def __init__(
6160
self,
6261
provided: Mapping[str, Any] | None,
6362
factories: Mapping[str, Callable[[], Any]],
6463
):
65-
# wrap to prevent modification escaping
66-
self.ready = dict(provided or {})
67-
# drop duplicate keys so the len and iter methods are easier
68-
self.lazy = {k: v for k, v in factories.items() if k not in self.ready}
69-
70-
def __contains__(self, key: Any) -> bool:
71-
return key in self.ready or key in self.lazy
72-
73-
def __len__(self) -> int:
74-
# Can just add the lengths as the keys are distinct by construction
75-
return len(self.ready.keys()) + len(self.lazy.keys())
64+
super().__init__(dict.fromkeys(factories, _EMPTY) | dict(provided or {}))
65+
self.lazy = dict(factories)
7666

7767
def __getitem__(self, key: str) -> Any:
78-
if key in self.ready:
79-
return self.ready[key]
80-
if factory := self.lazy.pop(key, None):
81-
value = factory()
82-
self.ready[key] = value
83-
return value
84-
raise KeyError(key)
85-
86-
def __iter__(self):
87-
return itertools.chain(self.lazy.keys(), self.ready.keys())
68+
if self.data[key] is _EMPTY:
69+
self.data[key] = self.lazy[key]()
70+
return self.data[key]
8871

8972

9073
class DeviceFactory(Generic[Args, V2]):

0 commit comments

Comments
 (0)