Skip to content

rlcompleter suggests attributes not accessible on instances (e.g., Enum member __name__) #139819

Description

@ttw225

Bug report

Bug description:

While looking into gh-139398, I noticed a separate issue: some tab-completion suggestions are offered even though they do not actually exist / are not accessible.

For example, on an Enum member, __name__ is suggested but accessing it raises AttributeError. Tracing the behavior shows rlcompleter includes class-level names even when they aren’t accessible from the instance; adding a guard in rlcompleter fixes it (PR incoming).

Reproduce

fromenumimportEnumclassColor(Enum):
BLUE=1# In the REPL, press <TAB> after typing:Color.BLUE.__# '__name__' appears in the suggestions.Color.BLUE.__name__# AttributeError: 'Color' object has no attribute '__name__'

Expected

Only attributes actually accessible on the instance should be suggested.

Actual

Class-level names show up for instances (e.g., Enum members), leading to AttributeError when accessed.

Fix

diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py
index 23eb0020f42..521f41a869d 100644
--- a/Lib/rlcompleter.py+++ b/Lib/rlcompleter.py@@ -39,6 +39,9 @@
__all__ = ["Completer"]
+# Sentinel object to distinguish "missing" from "present but None"+_SENTINEL = object()+
class Completer:
def __init__(self, namespace = None):
"""Create a new completer for the command line.
@@ -188,9 +191,9 @@ def attr_matches(self, text):
# property method, which is not desirable.
matches.append(match)
continue
- if (value := getattr(thisobject, word, None)) is not None:+ if (value := getattr(thisobject, word, _SENTINEL)) is not _SENTINEL:
matches.append(self._callable_postfix(value, match))
- else:+ elif word in getattr(type(thisobject), '__slots__', ()):
matches.append(match)
if matches or not noprefix:
break

Also observed (bogus suggestions)

['Color.BLUE.__iter__',
'Color.BLUE.__getitem__',
'Color.BLUE.__members__',
'Color.BLUE.__contains__',
'Color.BLUE.__qualname__',
'Color.BLUE.__len__',
'Color.BLUE.__name__']
# Additionally seen among bogus suggestions:
'Enum.__abstractmethods__'

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions