Language design
Markus Rother
python at markusrother.de
Wed Sep 11 16:41:50 EDT 2013
Hello all,
Thanks for this thread. Here are my two cents...
On 10.09.2013 08:09, Steven D'Aprano wrote:
> What design mistakes, traps or gotchas do you think Python has? Gotchas
> are not necessarily a bad thing, there may be good reasons for it, but
> they're surprising.
"""
1. Occasionally, one encounters a strange idiom. Syntactically
legal and consistent, though:
>>> +4++4
8
>>> -4+-4
-8
>>> -4-+4
-8
2. Reduce removed from standard library. That is a big fail, in
my opinion.
3. The default return value of methods is None instead of self.
If it was self, it would be possible to chain method calls (which
is called a cascade in smalltalk).
>>> lst = []
>>> lst.append(1).append(2).append(3) ## FAIL
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'append'
Instead, this works:
>>> class Coll(list):
...
... def add(self, e):
... self.append(e)
... return self
...
>>> lst = Coll()
>>> lst.add(1).add(2).add(3) ## OK
[1, 2, 3]
A very practical use case is, that the return value of None makes
all of these methods unusable for reduce.
>>> from functools import reduce
...
>>> many = [{1: 'a'}, {2: 'b'}, {3: 'c'}]
...
>>> reduce(lambda d, other : d.update(other), many, {}) ## FAIL
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'update'
Again, one would have to define an update function with an
explicit return value.
>>> many = [{1: 'a'}, {2: 'b'}, {3: 'c'}]
...
>>> def fn(d, other):
... d.update(other)
... return d
...
>>> reduce(fn, many, {}) ## OK
{1: 'a', 2: 'b', 3: 'c'}
4. As has been mentioned already, some built-in functions do magic
stuff behind the scenes:
>>> () == []
False
But:
>>> bool(().__eq__([]))
True
Because:
>>> ().__eq__([])
NotImplemented
which yields True when cast to boolean.
"""
Greets,
Markus
More information about the Python-list
mailing list