Skip to content

Safer attribute suggestion for classes with custom "bad" __dir__ย #139933

@Locked-chess-official

Description

@Locked-chess-official

Feature or enhancement

Proposal:

Now python suggest for attribute possible in this way:

        obj = exc_value.obj
        try:
            try:
                d = dir(obj)
            except TypeError:  # Attributes are unsortable, e.g. int and str
                d = list(obj.__class__.__dict__.keys()) + list(obj.__dict__.keys())
            d = sorted([x for x in d if isinstance(x, str)])
            hide_underscored = (wrong_name[:1] != '_')
            if hide_underscored and tb is not None:
                while tb.tb_next is not None:
                    tb = tb.tb_next
                frame = tb.tb_frame
                if 'self' in frame.f_locals and frame.f_locals['self'] is obj:
                    hide_underscored = False
            if hide_underscored:
                d = [x for x in d if x[:1] != '_']
        except Exception:
            return None

However, the obj may has no attribute "__dict__" if it has the attribute "__slots__". So list(obj.__class__.__dict__.keys()) + list(obj.__dict__.keys()) is not safe. And the class must have the attribute "__name__" that the object of the class cannot get.
In fact, the object.__dir__ is safer, it can exactly find all of the attribute that can be get with object.__getattribute__. So I think that we can change the way by using this way.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

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