@@ -570,9 +570,36 @@ def __rmatmul__(self, other):
570570 return False
571571
572572
573+ # Global cache with LRU eviction to prevent memory leaks
574+ _jsonpath_cache = OrderedDict ()
575+ _CACHE_MAX_SIZE = 128
576+
577+
578+ def _get_cached_jsonpath (expr : str ) -> JSONPath :
579+ """Get or create a cached JSONPath instance.
580+
581+ Args:
582+ expr: JSONPath expression string
583+
584+ Returns:
585+ Cached or newly created JSONPath instance
586+ """
587+ if expr in _jsonpath_cache :
588+ # Move to end (mark as recently used)
589+ _jsonpath_cache .move_to_end (expr )
590+ else :
591+ # Evict oldest if cache is full
592+ if len (_jsonpath_cache ) >= _CACHE_MAX_SIZE :
593+ _jsonpath_cache .popitem (last = False ) # Remove oldest (FIFO)
594+ _jsonpath_cache [expr ] = JSONPath (expr )
595+ return _jsonpath_cache [expr ]
596+
597+
573598def compile (expr ):
574599 """Compile a JSONPath expression for reuse.
575600
601+ Returns a cached JSONPath instance when available, avoiding redundant parsing.
602+
576603 Args:
577604 expr: JSONPath expression string
578605
@@ -584,16 +611,11 @@ def compile(expr):
584611 >>> jp.parse(data1)
585612 >>> jp.parse(data2)
586613 """
587- return JSONPath (expr )
588-
589-
590- # global cache with LRU eviction to prevent memory leaks
591- _jsonpath_cache = OrderedDict ()
592- _CACHE_MAX_SIZE = 128
614+ return _get_cached_jsonpath (expr )
593615
594616
595617def search (expr , data ):
596- """Search JSON data using JSONPath expression with LRU caching.
618+ """Search JSON data using JSONPath expression with caching.
597619
598620 Args:
599621 expr: JSONPath expression string
@@ -602,12 +624,4 @@ def search(expr, data):
602624 Returns:
603625 List of matched values
604626 """
605- if expr in _jsonpath_cache :
606- # Move to end (mark as recently used)
607- _jsonpath_cache .move_to_end (expr )
608- else :
609- # Evict oldest if cache is full
610- if len (_jsonpath_cache ) >= _CACHE_MAX_SIZE :
611- _jsonpath_cache .popitem (last = False ) # Remove oldest (FIFO)
612- _jsonpath_cache [expr ] = JSONPath (expr )
613- return _jsonpath_cache [expr ].parse (data )
627+ return _get_cached_jsonpath (expr ).parse (data )
0 commit comments