Skip to content

Add __len__() method to types.SimpleNamespace #136109

Open
@TomasCorreia2003

Description

@TomasCorreia2003

Feature or enhancement

Proposal:

SimpleNamespace is a useful lightweight object container, but currently:

from types import SimpleNamespace
ns = SimpleNamespace(a=1, b=2)
len(ns)  # Raises TypeError

Adding a len() method would improve its usability by allowing:

len(ns)  # returns 2

This matches user expectations since its attributes are stored in dict.

Proposed Implementation:
Define:

def __len__(self):
    return len(self.__dict__)

This is simple, backwards-compatible, and testable.

Benefits:
Improves discoverability

Makes SimpleNamespace feel more like a container

Zero risk of breakage

I would like to implement this as a small contribution.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions