@@ -476,20 +476,34 @@ def _get_item_lookup_completions(
476
476
Complete dictionary keys.
477
477
"""
478
478
479
- def meta_repr (value : object ) -> Callable [[], str ]:
479
+ def meta_repr (obj : object , key : object ) -> Callable [[], str ]:
480
480
"Abbreviate meta text, make sure it fits on one line."
481
+ cached_result : str | None = None
481
482
482
483
# We return a function, so that it gets computed when it's needed.
483
484
# When there are many completions, that improves the performance
484
485
# quite a bit (for the multi-column completion menu, we only need
485
486
# to display one meta text).
487
+ # Note that we also do the lookup itself in here (`obj[key]`),
488
+ # because this part can also be slow for some mapping
489
+ # implementations.
486
490
def get_value_repr () -> str :
487
- text = self ._do_repr (value )
491
+ nonlocal cached_result
492
+ if cached_result is not None :
493
+ return cached_result
494
+
495
+ try :
496
+ value = obj [key ] # type: ignore
497
+
498
+ text = self ._do_repr (value )
499
+ except BaseException :
500
+ return "-"
488
501
489
502
# Take first line, if multiple lines.
490
503
if "\n " in text :
491
504
text = text .split ("\n " , 1 )[0 ] + "..."
492
505
506
+ cached_result = text
493
507
return text
494
508
495
509
return get_value_repr
@@ -504,24 +518,24 @@ def get_value_repr() -> str:
504
518
# If this object is a dictionary, complete the keys.
505
519
if isinstance (result , (dict , collections_abc .Mapping )):
506
520
# Try to evaluate the key.
507
- key_obj = key
521
+ key_obj_str = str ( key )
508
522
for k in [key , key + '"' , key + "'" ]:
509
523
try :
510
- key_obj = ast .literal_eval (k )
524
+ key_obj_str = str ( ast .literal_eval (k ) )
511
525
except (SyntaxError , ValueError ):
512
526
continue
513
527
else :
514
528
break
515
529
516
- for k , v in result . items () :
517
- if str (k ).startswith (str ( key_obj ) ):
530
+ for k in result :
531
+ if str (k ).startswith (key_obj_str ):
518
532
try :
519
533
k_repr = self ._do_repr (k )
520
534
yield Completion (
521
535
k_repr + "]" ,
522
536
- len (key ),
523
537
display = f"[{ k_repr } ]" ,
524
- display_meta = meta_repr (v ),
538
+ display_meta = meta_repr (result , k ),
525
539
)
526
540
except ReprFailedError :
527
541
pass
@@ -537,7 +551,7 @@ def get_value_repr() -> str:
537
551
k_repr + "]" ,
538
552
- len (key ),
539
553
display = f"[{ k_repr } ]" ,
540
- display_meta = meta_repr (result [ k ] ),
554
+ display_meta = meta_repr (result , k ),
541
555
)
542
556
except KeyError :
543
557
# `result[k]` lookup failed. Trying to complete
0 commit comments