Comment

Comment by praptak

I have a mildly surprising snippet which I believe they don't have. It's about interaction of class and instance attributes with behavior of "X += Y". Python expands it to "X = X + Y" but only if X implements "+" but not "+="

    class A:
        a = (1,)  # tuples are immutable and don't have "+="
        b = [1,]  # lists have "+="
   
    obj = A()
    obj.a += (2,)  # this creates obj.a
    obj.b += (2,)  # this modifies A.b

    print(A.a, A.b)
The snippet prints "(1,) [1,2]".
parent praptak 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton