Skip to content

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

@ttw225

Description

@ttw225

Bug report

Bug description:

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

from enum import Enum
class Color(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..1a0c8ef000c 100644
--- a/Lib/rlcompleter.py
+++ b/Lib/rlcompleter.py
@@ -190,7 +190,7 @@ def attr_matches(self, text):
                         continue
                     if (value := getattr(thisobject, word, None)) is not None:
                         matches.append(self._callable_postfix(value, match))
-                    else:
+                    elif hasattr(thisobject, word):
                         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