Issue 1276587: dict('') doesn't raise a value error (original) (raw)

Logged In: YES user_id=31435

It's not theoretical: it's a fact that dict() accepts any iterable producing iterables each producing 2 objects (the latter don't have to be tuples; a (key, value) tuple is just one kind of iterable producing 2 objects; e.g., dict(["ab"]) == {'a': 'b'}).

An empty str meets the input requirements, so there's no way to stop this without special-case type-sniffing. That's very unattractive, in part because it's impossible to guess which kinds of empty iterables would necessarily lead to an exception when passed to dict() had they not been empty.
For example, passing an empty array.array (of any flavor) to dict() also constructs an empty dict. The universe of iterable objects is vast.

Keeping it uniform and easy to explain (an empty iterable produces an empty dict) seems better to me than adding a maze of special cases that's bound to change over time ("except for an empty str" ... "oh, or an empty unicode" ... "oh, or an empty array.array" ... "oh, or an empty file" ... "oh, oops, guess not, cuz a file with two lines works fine" ... etc).