1010import asyncio
1111import importlib
1212import re
13+ from operator import itemgetter
1314from typing import Awaitable , Callable , Protocol , cast , final
1415
1516from apywire .constants import SYNTHETIC_CONST
@@ -154,20 +155,17 @@ def _separate_args_kwargs(
154155 Returns:
155156 Tuple of (positional_args, keyword_args)
156157 """
157- args_list : list [ tuple [ int , object ]] = []
158- kwargs_dict : dict [ str , object ] = {}
159-
158+ # Iterate once over data.items() to separate args and kwargs
159+ args_list = []
160+ kwargs_dict = {}
160161 for k , v in data .items ():
161162 if isinstance (k , int ):
162163 args_list .append ((k , v ))
163164 else :
164165 kwargs_dict [k ] = v
165166
166- # Sort positional args by index
167- def _sort_key (item : tuple [int , object ]) -> int :
168- return item [0 ]
169-
170- args_list .sort (key = _sort_key )
167+ # Sort positional args by index and extract values
168+ args_list .sort (key = itemgetter (0 ))
171169 pos_args = [v for _ , v in args_list ]
172170
173171 return (pos_args , kwargs_dict )
@@ -244,8 +242,6 @@ def _instantiate_impl(self, name: str) -> _RuntimeValue:
244242 # All positional arguments
245243 instance = constructor (* kwargs )
246244 else :
247- # Should not happen given _ResolvedSpecMapping type,
248- # but for safety
249245 instance = constructor (kwargs )
250246 except Exception as e :
251247 raise WiringError (
@@ -267,9 +263,7 @@ def _resolve_runtime(
267263 their accessors.
268264 """
269265 if isinstance (o , _WiredRef ):
270- # Detect when a placeholder reference points to something that
271- # wasn't defined in the spec. This is an unknown placeholder
272- # and should raise a friendly error.
266+ # Ensure placeholder was defined in spec
273267 if o .name not in self ._values and o .name not in self ._parsed :
274268 ctx = f" while instantiating '{ context } '" if context else ""
275269 raise UnknownPlaceholderError (
@@ -280,11 +274,11 @@ def _resolve_runtime(
280274 # Call the accessor `self.name()` to get the runtime value.
281275 return cast (object , getattr (self , o .name )())
282276
283- if isinstance (o , dict ):
277+ elif isinstance (o , dict ):
284278 return {k : self ._resolve_runtime (v , context ) for k , v in o .items ()}
285- if isinstance (o , list ):
279+ elif isinstance (o , list ):
286280 return [self ._resolve_runtime (v , context ) for v in o ]
287- if isinstance (o , tuple ):
281+ elif isinstance (o , tuple ):
288282 return tuple (self ._resolve_runtime (v , context ) for v in o )
289283 return o
290284
@@ -348,11 +342,12 @@ def __init__(self, wiring: WiringRuntime, name: str) -> None:
348342
349343 def __call__ (self ) -> object :
350344 """Return the wired object, instantiating it if necessary."""
351- # Fast path: check if already instantiated and cached in _values
352- # or as an attribute on the instance.
353- # We check _values first as it is the canonical storage.
354- if self ._name in self ._wiring ._values :
345+ # Fast path: EAFP pattern for cache lookup
346+ # Try to get cached value directly (faster than check + get)
347+ try :
355348 return self ._wiring ._values [self ._name ]
349+ except KeyError :
350+ pass
356351
357352 # Not cached, so we need to instantiate it.
358353 # We use _instantiate_attr which handles thread safety if enabled.
@@ -381,9 +376,11 @@ def __getattr__(self, name: str) -> Callable[[], Awaitable[object]]:
381376 )
382377
383378 async def _get () -> object :
384- # If already cached, return immediately
385- if name in self . _wiring . _values :
379+ # EAFP: Try cached value first
380+ try :
386381 return self ._wiring ._values [name ]
382+ except KeyError :
383+ pass
387384
388385 # If not cached, run instantiation in executor to avoid blocking
389386 # the event loop.
0 commit comments