[Python] Why doesn't len(obj) go through __getattribute__, and how can I override this...

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I've noticed that calling obj.__len__() explicitly goes through obj.__getattribute__("__len__"), but calling len(obj) does not. A quick search suggests that built - in functions like len(), dir(), and repr() optimize their calls by accessing attributes directly via the object's internal structure rather than going through __getattribute__, except when dealing with private attributes.

    Even if I clear obj.__dict__, len(obj) still bypasses __getattribute__. I also tried overriding obj.__dir__() and removing all dunder methods it returns, but len(obj) still avoids __getattribute__.

    Is there any way to override this behavior and force len(obj) (and the others) to go through __getattribute__("__len__")?

    Exaple:

    class Custom:
    def __getattribute__(self, item):
    print(f"Accessing: {item}")
    return super().__getattribute__(item)

    def __len__(self):
    return 50

    obj = Custom()

    print(obj.__len__()) # Triggers __getattribute__
    print(len(obj)) # Bypasses __getattribute__


    Output:

    Accessing: __len__
    50
    50 # No `Accessing: __len__` message, meaning __getattribute__ was bypassed

    Continue reading...

Compartilhe esta Página