Skip to content

Commit a204c76

Browse files
Improve dictionary completion performance.
This improves the performance for dictionary-like objects where iterating over the keys is fast, but doing a lookup for the values is slow. This change ensures we only do value lookups when really needed.
1 parent 79cb14b commit a204c76

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

ptpython/completer.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -476,15 +476,20 @@ def _get_item_lookup_completions(
476476
Complete dictionary keys.
477477
"""
478478

479-
def meta_repr(value: object) -> Callable[[], str]:
479+
def meta_repr(obj: object, key: object) -> Callable[[], str]:
480480
"Abbreviate meta text, make sure it fits on one line."
481481

482482
# We return a function, so that it gets computed when it's needed.
483483
# When there are many completions, that improves the performance
484484
# quite a bit (for the multi-column completion menu, we only need
485485
# to display one meta text).
486486
def get_value_repr() -> str:
487-
text = self._do_repr(value)
487+
try:
488+
value = obj[key] # type: ignore
489+
490+
text = self._do_repr(value)
491+
except BaseException:
492+
return "-"
488493

489494
# Take first line, if multiple lines.
490495
if "\n" in text:
@@ -504,24 +509,24 @@ def get_value_repr() -> str:
504509
# If this object is a dictionary, complete the keys.
505510
if isinstance(result, (dict, collections_abc.Mapping)):
506511
# Try to evaluate the key.
507-
key_obj = key
512+
key_obj_str = str(key)
508513
for k in [key, key + '"', key + "'"]:
509514
try:
510-
key_obj = ast.literal_eval(k)
515+
key_obj_str = str(ast.literal_eval(k))
511516
except (SyntaxError, ValueError):
512517
continue
513518
else:
514519
break
515520

516-
for k, v in result.items():
517-
if str(k).startswith(str(key_obj)):
521+
for k in result:
522+
if str(k).startswith(key_obj_str):
518523
try:
519524
k_repr = self._do_repr(k)
520525
yield Completion(
521526
k_repr + "]",
522527
-len(key),
523528
display=f"[{k_repr}]",
524-
display_meta=meta_repr(v),
529+
display_meta=meta_repr(result, k),
525530
)
526531
except ReprFailedError:
527532
pass
@@ -537,7 +542,7 @@ def get_value_repr() -> str:
537542
k_repr + "]",
538543
-len(key),
539544
display=f"[{k_repr}]",
540-
display_meta=meta_repr(result[k]),
545+
display_meta=meta_repr(result, k),
541546
)
542547
except KeyError:
543548
# `result[k]` lookup failed. Trying to complete

0 commit comments

Comments
 (0)