Skip to content

Allow obj[key] to fallback to attribute-based __getitem__ #141980

@bilibili12433014

Description

@bilibili12433014

Feature or enhancement

Proposal:

In current Python, the expression:

obj[key]

only works if the type defines a mapping or sequence slot.
If it does not, Python immediately raises TypeError, even if the object does provide a __getitem__ method dynamically.

This leads to surprising limitations for objects that delegate or map behavior to another object.

Example

Suppose we have an object acting as a dynamic view or proxy:

class ConfigView:
    def __init__(self, target):
        self.target = target

    def __getattr__(self, name):
        # forward lookups to the underlying object
        return getattr(self.target, name)

If the underlying object implements __getitem__, we would naturally expect:

view["path"]

to work the same as:

view.target["path"]

But currently it fails with:

TypeError: 'ConfigView' object is not subscriptable

even though __getitem__ is available via attribute lookup.

Proposal

When a type does not provide a mapping or sequence slot, allow obj[key] to fall back to an attribute lookup for __getitem__, following normal attribute resolution rules (__getattribute__, __getattr__, delegation, etc.).

This would make subscripting consistent with other special methods that already allow attribute-based fallback, and it would significantly improve the behavior of dynamic proxy objects.

I would like to hear thoughts on whether this fallback would be acceptable as an enhancement.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions