On Mon, Oct 30, 2017 at 07:14:10AM +0300, Ivan Pozdeev via Python-ideas wrote:

> The eponymous C#'s LINQ method, I found very useful in the following, 
> quite recurring use-case:

If I have understood your use-case, you have a function that returns a 
list of results (or possibly an iterator, or a tuple, or some other 
sequence):

    print(search(haystack, needle))
    # prints ['bronze needle', 'gold needle', 'silver needle']

There are times you expect there to be a single result, and if there are 
multiple results, that is considered an error. Am I correct so far?

If so, then sequence unpacking is your friend:

    result, = search(haystack, needle)

Note the comma after the variable name on the left-hand side of the 
assignment. That's a special case of Python's more general sequence 
unpacking:

    a, b, c = [100, 200, 300]

assigns a = 100, b = 200, c == 300. Using a single item is valid:

py> result, = [100]
py> print(result)
100


but if the right-hand side has more than one item, you get an exception:

py> result, = [100, 200, 300]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)


I *think* this will solve your problem.

If not, can you please explain what "single()" is supposed to do, why it 
belongs in itertools, and show an example of how it will work.


-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to