+1 for itertools.first(seq, default=Exception) *and* itertools.one(seq,
default=Exception)

This is a very common pattern (particularly with RDF / JSON-LD (@type)
where there can be multiple instances of any predicate-object /
attribute-value pair)

SQLAlchemy also has .first(), .one(), and .one_or_none() (with no default=
and sqlalchemy.orm.exc.NoResultFound and
sqlalchemy.orm.exc.MultipleResultsFound)

On Sat, Dec 7, 2019, 9:20 AM Kirill Balunov <[email protected]> wrote:

>
> сб, 7 дек. 2019 г. в 03:45, Steven D'Aprano <[email protected]>:
>
>> This is how I would implement the function in Python:
>>
>>     def first(iterable, default=None):
>>         return next(iter(iterable), default)
>>
>
> A somewhat related discussion was somewhere inside November 2017
> <https://mail.python.org/archives/list/[email protected]/thread/QX6IRM4SNCK74IYQNFOCLDAZ5RIIRUKL/>
> thread "How assignment should work with generators?". The main idea was
> to extend assignment syntax to something like `first, second, ... = gen`
> which should be equivalent to `first, second, ... = next(gen), next(gen)`.
> Another idea was (but nobody liked it) to change the behavior of `x, y,
> *tail = iter` to not to consume starred part and to make a generator
> instead of list. I understand that the topic discussed here is slightly
> different, but in my understanding it is all the eggs of one chicken.
>
> I still like the idea of partial assignment syntax `x, y, ... = iter` but as
> well as then, I understand that I don’t have enough English knowledge and
> time to write a proposal on that topic and especially to follow thread and
> to defend an idea :( The main objection was that this all is easy
> achievable with `islice` from `itertools`.
>
> Back to the topic - maybe `first` is a good citizen for `itertools`
> module. Because this idea (about first ) is discussed constantly every
> two years.
>
> with kind regards,
> -gdg
> _______________________________________________
> Python-ideas mailing list -- [email protected]
> To unsubscribe send an email to [email protected]
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/[email protected]/message/D7ALA5XP43IWLMMGYSD43FLUSRA3OTAL/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/6EGLIANRPF3KYXP6NUGG2XGSMVMAPSGQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to