3 ms·
My favorite function here is more_itertools.one. Especially in something like a unit test, where ValueErrors from unexpected conditions are desirable, we can us
by benkuykendall 2y ago
My favorite function here is more_itertools.one. Especially in something like a unit test, where ValueErrors from unexpected conditions are desirable, we can use it to turn code like
results = list(get_some_stuff(...))
assert len(results) = 1
result = results[0]
into
result = one(get_some_stuff(...))
I guess you could also use tuple-unpacking:
result, = get_some_stuff(...)
But the syntax is awkward to unpack a single item. Doesn't that trailing comma just look implausible? (Also I've worked with type-checkers that will complain when a tuple-unpacking could potentially fail, while one has a clear type signatures Iterable[T] -> T.)
- rjmill 2y agoYou can also do [result] = get_some_stuff(...)
- adammarples 2y agoDo tuple unpacking like this result, _* = iterable()
- plyp 2y agoThat’s not the same though. Your unpacking allows for any non-empty iterable while OPs only allows for an iterable with exactly one item or else it throws an exception.