by praptak · 4y ago · 0 comments
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]".Ya, this is because the initialized object is stored as the default parameter, and is not initialized every time the function runs.
def functy(dicty={}):
print('dicty=', dicty)
return dicty
output = functy()
# dicty = {}
output.update({'key': 'value'})
functy()
# dicty = {'key': 'value'}I think this behavior is actually "default args" but reversed. In case of default args it is the mutability that causes the nasty surprise (ooops, all calls share the same object, which is mutable). In case of the "+=" it is the _immutability_ that causes the surprise - I would not expect "obj.a += ..." to create an instance attribute that shadows the class one.
I think the practical conclusion here is "don't call += on objects that don't support it - because it may work and this is not what you want!)".
I'm curious if you see it the same way?
It seems to, but, actually, it doesn't.
> but wtf'ingly also alters the value of the class attribute "A.b" which completely alters the behavior of A.
Actually, all it does is call the __iadd__ method on the list that it is the value of A.b (which modifies that list in-place.)
The value of A.b can, incidentally be accessed via obj.b because obj.b does not exist and the lookup path for instance attributes includes the class.
There are two things going on here there are potential sources of confusion, because they behavior differently in different circumstances: object member access (which can get members from the object or, if they don't exist on the object, from the class) and the += operator, which calls the __iadd__ method on the left value or acts as add and then assign to the name on the left, if that name doesn't reference a value that supports __iadd__.
Side note: the object can be immutable, but then the (variable or attribute) left side should be replaced with a new immutable object.
It necessarily alters the value of A.b, since `+=` is specifically overridden to update the list in-place. With lists, `a += b` is specifically not an alias for `a = a + b`, instead its behaviour is closer to
a.extend(b)
a = a
The issue here is the first part, I absolutely hate this override, and sadly the core team has not learned a thing there as `|=` was overridden the exact same way on dicts when `dict | dict` was added to the language.Note to readers unfamiliar with Python: class attributes is a special thing, different than instance attributes.
Definitely one of the trickier things with Python for sure.
async function totalSize(fol) {
const files = await fol.getFiles();
let totalSize = 0;
await Promise.all(files.map(async file => {
totalSize += await file.getSize();
}));
// totalSize is now way too small
return totalSize;
}
You get an overly low totalSize. It's caused by 'a += b' expanding to 'a = a + b', and the double-mention of 'a' creating a concurrency issue. If '+=' were a single operation with the right-hand-side being calculated first, it wouldn't be an issue.I guess the problem in python is different though, it's about having some data structures that are immutable (like tuple) and others that are mutable (like list)
To fix this, simply await the result of getSize first, and then add the result to totalSize using +=
That is the sole source of the issue, and exactly what the comment you're replying to talks about.
The problem is that `a += b` desugars to `a = a + b`, so if `b` is an await you get
totalSize = totalSize + await file.getSize();
Since javascript evaluates left to right, it first evaluates `totalSize`, gets zero, then `file.getSize()`, then suspends waiting for the result... at which point the handler for the next file can run, doing the exact same thing, repeat for all files.That must have been a fun one to track down!
class A:
a = (1,)
b = [1,]
def __init__(self):
self.a = (1,)
self.b = [1,]
A.a # this is the class attribute
(1,)
A.b # class attribute
[1]
obj = A()
obj.a # instance attribute
(1,)
obj.b
[1]
obj.a += (2,)
obj.b += [2,]
A.a
(1,) # still the same class attribute
A.b
[1]
obj.a
(1, 2) # instance attribute appended
obj.b
[1, 2]If I had had magic wand, I'd make operations on class attributes from an instance a syntax error, and only allow it from the class name, and perhaps with special syntax like in C++, e.g.:
A::a = (1,)
A::b = [1,]
*edit: operation on obj.a or obj.b...> # tuples are immutable and don't have "+="
What do you mean? Because it looks to me tuples have "+=":
a = (1,)
a += (3,)
# a = (1, 3)
I get that tuple is immutable so you're actually creating a new tuple and shove it back into variable a, but it does not conflict with "having += operation".Python is more of a lisp. The assignment semantics are different to C. Actually, you're letting the name "a" point to the newly created object.
In C, a variable is a memory position you can fill and point to.
In Python, a variable is a name that points to a memory position.
Similarity to C is no accident here, since the lexical scoping concepts in Lisps like Scheme and CL, as well as in C, both trace back to Algol.
Classic Lisp global/dynamic variables may store a global value a "value cell" which is closely tied to the symbol itself (perhaps stored in it).
And in that sense, C assignment and Lisp assignment are different beasts. Mainly in that - again in the semantics of the high-level description - "memory reservation" in C happens when we declare the left-hand side of an assignment and in Lisp it happens when we construct the right-hand side.
Though if you can show me a mainstream Lisp where the assignment works like setting a memory cell and not like a bind, I'm happy to be proven wrong.
Thanks!
But if l does support __iadd__, then l += r becomes l.__iadd__(r).
This behavior for list and tuple is familiar from regular local variables. Together with the fact that obj.x = ... always means "create or rebind an instance variable" never "rebind the A.x class variable", I think the example is less surprising.
>>> print(obj.a, obj.b)
(1, 2) [1, 2]