>>> {} + {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> bool({})
False
Since I find bool(a_dict) to be very useful, and the lack of a_dict+b_dict to be reasonable (precisely because it's non-abelian!), I conclude that logic is cute, but not that relevant.Those who think it this argument is pursuasive, should bool({}) raise an exception? Or should {1:"A"}+{1:"B"} not raise an exception and instead return ... what?
Or do I misunderstand something?
In any case, it's a bit of a distraction. "Most programmers" aren't all that good at programming, or judging what makes a good language. How important then is it that I weigh your projection of their ideas of right or wrong?
In Python it absolutely, positively, without a doubt is not a bad thing to have a function which accepts multiple data types. Some trivial examples are len() and iter(). Since you don't like the core language design in Python, I think it's safe to argue that your sensibilities are going to have many objections to any other part of the language.
> In Python it absolutely, positively, without a doubt is not a bad thing to have a function which accepts multiple data types. Some trivial examples are len() and iter().
I'm not arguing that this shouldn't be the case. My argument is specifically about bool(). If len() or iter() worked as strangely with basic data types as bool(), then I would probably extend my argument to cover them as well. For any data type I'm aware of that works with len() or iter(), the logic of what is returned is pretty clear and obvious, but that's not the case (in my opinion) with bool(). If len(-5) returned 5 (i.e. absolute value or "length from zero") then I would argue that it's a bad idea.
[xebulon:~/tmp] dalke% cat tmp.cc
#include <iostream>
template<typename T>
int f(T s) {
return s ? 2 : 0;
}
main() {
std::cout << "int 0 " << f(0) << std::endl;
std::cout << "int 8 " << f(8) << std::endl;
std::cout << "float 0.0 " << f(0.0) << std::endl;
std::cout << "float -1.0 " << f(-1.0) << std::endl;
}
[xebulon:~/tmp] dalke% g++ tmp.cc
[xebulon:~/tmp] dalke% ./a.out
int 0 0
int 8 2
float 0.0 0
float -1.0 2
The function f() doesn't know the type, but its instantiation for f(0) (integer) and f(0.0) float know the type.C++ containers don't have a bool (or at least vector<> doesn't). For one, until C++11 there was no "explicit operator bool", and a simple "operator bool" was too permissive because of implicit type conversion. C++11 introduced a more contextual conversion to bool.
More and more components have explicit bool support. For example, http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/shared_p... ?
Notes: This conversion operator allows shared_ptr objects to be
used in boolean contexts, like if(p && p->valid()) {}.
[The conversion to bool is not merely syntactic sugar. It allows shared_ptrs
to be declared in conditions when using dynamic_pointer_cast
or weak_ptr::lock.]
and http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_... .I do not track C++ well enough to go into any more depth than this, especially as it concerns the history and future.
I like to say "if x: ..." and not "if len(x) == 0:" in order to check if a dictionary is empty.
Following Scheme, I can understand that something like "if empty(x)" might be more explicit. But I have a decent amount of code where I do something like:
def process(a, rename=None):
if rename:
a = [rename.get(x, x) for x in a]
... do things with a ...
In this toy example, "rename=None" indicates that there is no renaming dictionary, and using {} as the renaming dictionary won't rename anything, so the "if rename" tests for both conditions correctly.Without bool, I could write it as:
if rename is not None:
since using the empty dictionary in this case is okay, but if I want the slight extra performance for the empty dictionary case I would have to write it: if rename is not None and not empty(rename):
I think that would grow tedious.BTW, I don't use "def process(a, rename={}):" because that is one of Python anti-patterns: the default values are constant over the life of the function, so
def something(a, b={}):
b[a] = a
return b
will accumulate to b rather than create a new dictionary each time. Thus, seeing a "={}" or "=[]" in a parameter list demands closer inspection because it often leads to errors.You could try to define the addition of keys like you suggest, but you need to force a value type which defines a + operation into the same type. Which is what Counter() does, below (appending strings).
Python is dynamically typed, so you can't maintain these expectations. Therefore, summation and bool({}) should be an error, or merely "true" (ie, yes, it exists, and is not None) -- as per the original thread and resolution.
{1: "A"} + {}
Should that return {1: ["A"]}? In which case {} is no longer a zero value.What about
{1: "A"} + {} + {1: "B", 2: "Z"} + {1: "C"} + {}
In any case, your suggestion would break all existing code. Based on all the StackOverflow and python-list questions, most people expect one or the other value, and few want the two-element list containing both. (And why a list instead of a tuple?)Guido chose the current behavior because there is no clear-cut winner. "Refuse the temptation to guess."
{1: "A"} + {} == {1: "A"}
but {1: "A"} + {} + {1: "B", 2: "Z"} + {1: "C"} + {}
should reduce to: {1: ("A" + "B" + "C"), 2: "Z"}
Whether you can add "A", "B", and "C" would depend on string functions (could be "ABC" or raise an exception that these cannot be added for example).If {1:"A"}+{} == {1:"A"} then the type of each value is unchanged from the input list.
If {1:"A"}+{1:"B"} == {1:["A","B"]} then the type of each value (or at least each shared value) is a 2-element list.
If both are true, then no one can write sane code which knows how deal with the sum of two dictionaries.
That is, the insane code has to have checks for if one of the dictionaries is empty, and if so, do one thing, otherwise do another thing. In which case, why is this definition useful?
Therefore, either {} is the zero value, or dictionary summation produces lists for the resulting values, but not both.
That's how it usually works with functions.
>>> from collections import Counter
>>> Counter({1: "a"}) + Counter({1: "b"})
Counter({1: 'ab'})
But Python dictionaries won't support '+' because of the ambiguity. This goes back to 1994: http://ftp.ntua.gr/mirror/python/search/hypermail/python-199... Lance Ellinghouse:
why can't I add dictionaries like I can other objects?
...
if a and b both had the same keys, then I think b should override
the keys in a.
and Kenneth Manheimer posted a dict-like implementation in http://ftp.ntua.gr/mirror/python/search/hypermail/python-199... which also has the replacement behavior.Guido responded in http://ftp.ntua.gr/mirror/python/search/hypermail/python-199... saying that he could think of no reason to prefer replacement over keep behavior.
In my own early Python code, I sometimes used + when I wanted an update semantic, so I can confirm that your expectations aren't universal.
And that's what this comes down to - is bool(time(0, 0))==False the generally expected behavior (which is a higher threshold than reasonable behavior)? What are the likely errors? Do the advantages outweigh the disadvantages?
That's why an argument about the zero element is only somewhat relevant - most programmers aren't mathematicians, and practicality beats purity.
>>> a = Counter()
>>> a[1] = a
>>> b = Counter()
>>> b[1] = b
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...../collections.py", line 536, in __add__
newcount = self[elem] + other[elem]
File "...../collections.py", line 534, in __add__
result = Counter()
RuntimeError: maximum recursion depth exceeded
If dict() implemented add as you propose then it would be subject to the same errors. This observation doesn't make your proposal wrong. I mean it to point out the subtle complexities which might come up if a large number of people don't know what it's supposed (and even documented) to do.That said, this is a good example of the expressivity of this, which mathematical definitions often implicitly disallow.
For example, NUL terminated strings lead to a lot of user errors, some of which lead to security holes. Other string representations don't have that flaw, though come with a different cost concern. Is a buffer overflow "user error"? Some would say it is. But the language design makes those errors more dangerous.
Or in Python, there's no technical reason to have a ":" at the end of the line before an indented block. Instead, it's there because user studies show that people learning ABC (which influenced a lot of early Python) made fewer mistakes if the ":" was present than if it wasn't.
Are indentation mistakes user error? Certainly users play a role. But again, the design does as well.
So saying that something is a "user error" with no further analysis absolves the designer of any responsibility, and I disagree with that idea.
There are at least 4 different ways to handle dict+dict in Python. At least three have come up in this thread as the proposed correct solution. Even if there is a mathematically clean solution, if only 10% of the people expect it to work that way, then why should Python introduce something which is so error prone? No support for dict+dict is 100% error prone, of course, but trivially identified in testing. While Counter+Counter-like behavior has subtle consequences that will trip people up.
(As another example of the subtleties, consider an inverted index mapping word to a list of document ids:
collection_a = {"a": [0, 3, 4], "the": [0, 2, 3]}
collection_b = {"a": [5], "an": [6, 7]}
collection_c = {"the": [10], "not": [10]}
merged_collection = a+b
merged_collection += collection_c
This is wrong because the += changes merged_collection["the"], which is the same list as collection_a["the"]. So even though it looks like good code, and it is good code for any value where x+=y is the same as x=x+y, it may cause problems which are hard to spot.)"In the face of ambiguity, resist the temptation to guess."
[] + [] == []
[1,2] + [3] != [3] + [1,2] if x:
<destructure x, recurse on subparts>
else:
return <something>
This applies to (natural) numbers as well--'destructuring' usually means decrementing the number. $ python
>>> import time, datetime
>>> () + ()
()
>>> "" + ""
''
>>> 0 + 0
0
>>> datetime.timedelta() + datetime.timedelta()
datetime.timedelta(0)
>>> time.time() + time.time()
27848327051.323207
Seems like time() + time() is not a TypeError in Python.time.time() returns the seconds elapsed since the epoch.
The code examples seem to be referring to the existence of an identity element, which is necessary for all groups.
The truth is, time doesn't have a sensible addition/combination operator, never mind an identity and inverse, so it isn't even a group.
This is venturing off topic, but if you really wanted to, you could define addition for times in terms of timedeltas. It makes sense to subtract times and get a timedelta, so you could define addition as the subtraction with signed times and signed timedeltas. So, since `time(today) - time(yesterday) = timedelta(1 day)`, we could say that `time(today) + time(yesterday) = -timedelta(1 day)` and `time(today) - -time(yesterday) = timedelta(1 day)`. It's a bit strange to define the notion of a signed time object, but it could work.
a + 0:00 = a
15:00 + 13:00 = 02:00
12:00 + 12:00 = 00:00
The examples are for hours only, but you can extend it for minutes too. Showing that time values on a clock forms an abelian group under addition is a textbook example everyone uses when introducing group theory.I'll assume the times you gave were in the UK's timezone. Here they are rewritten to use Germany's timezone.
a + 1:00 = a
16:00 + 14:00 = 03:00
13:00 + 13:00 = 01:00
Still think this makes sense?Time deltas? Then you don't have the timezone or epoch problem. Works fine.
But time stamps? You can't add two time stamps and get a sensible answer.
Time stamps form a torsor, not a group: http://math.ucr.edu/home/baez/torsors.html
edit: last Tuesday, 5:00pm + Christmas two years ago at noon = ???