M
Maric Michaud
Le Tuesday 16 September 2008 14:23:25 Armin, vous avez écrit :
It is, please try to understand it, in python all expressions that mutate an
object should return None, it's the case for
l.append(x)
l.sort()
l.reverse()
...
all expressions that return something, return a new object, it's the case for
1+2
1.__add__(2) (which is the same)
sorted(l)
l[i:j]
etc...
there are some noticeable exceptions :
For coding facilities, some APIs could return the modified part of the object,
ex : it = c.pop()
Returning the modifyied object itself is mostly considered bad style, because
it doesn't make clear if this the object or a copy. There is OTHO a use case
for this, for APIs that allow chaining of operations (don't find by memory
any example in stdlib, though), alike the ">>" operator in C++, but pyparsing
is a good example if I remember well. BTW, Pythoneers are not very fond of
that.
Finally, the very special case of augmented assignment operators :
x.__iadd__(y) which actually return the modified object, but this expression
isn't intended to be use by callers, refer to the manual to see a good
example of this, how one should implement __add__ and __iadd__ methods.
a += b
a = a + b
both are statments (doesn't evaluate to any object), but are not equivalent if
a is mutable.
Alex said:Armin said:Duncan Booth wrote:
The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c
(with c = [8,9]) is identical,
No it's not, + doesn't alter its operands.
a = 1
b = 2
a + b
3
That's not the point![]()
It is, please try to understand it, in python all expressions that mutate an
object should return None, it's the case for
l.append(x)
l.sort()
l.reverse()
...
all expressions that return something, return a new object, it's the case for
1+2
1.__add__(2) (which is the same)
sorted(l)
l[i:j]
etc...
there are some noticeable exceptions :
For coding facilities, some APIs could return the modified part of the object,
ex : it = c.pop()
Returning the modifyied object itself is mostly considered bad style, because
it doesn't make clear if this the object or a copy. There is OTHO a use case
for this, for APIs that allow chaining of operations (don't find by memory
any example in stdlib, though), alike the ">>" operator in C++, but pyparsing
is a good example if I remember well. BTW, Pythoneers are not very fond of
that.
Finally, the very special case of augmented assignment operators :
x.__iadd__(y) which actually return the modified object, but this expression
isn't intended to be use by callers, refer to the manual to see a good
example of this, how one should implement __add__ and __iadd__ methods.
a += b
a = a + b
both are statments (doesn't evaluate to any object), but are not equivalent if
a is mutable.