Different "look and feel" of some built-in functions

Chris Angelico rosuav at gmail.com
Fri Sep 24 20:58:05 EDT 2021


On Sat, Sep 25, 2021 at 10:56 AM Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> On Sat, 25 Sept 2021 at 00:37, Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
>
> > On 25/09/21 10:15 am, Steve Keller wrote:
> > > BTW, I like how the min() and max() functions allow both ways of being
> > > called.
> >
> > That wouldn't work for set.union and set.intersection, because as
> > was pointed out, they're actually methods, so set.union(some_seq)
> > is a type error:
> >
> >  >>> a = {1, 2}
> >  >>> b = {3, 4}
> >  >>> set.union([a, b])
> > Traceback (most recent call last):
> >    File "<stdin>", line 1, in <module>
> > TypeError: descriptor 'union' for 'set' objects doesn't apply to a
> > 'list' object
> >
> > I suppose they could be fiddled somehow to make it possible, but
> > that would be turning them into special cases that break the rules.
> > It would be better to provide separate functions, as was done with
> > sum().
> >
>
> A separate union function would be good. Even in a situation where all
> inputs are assured to be sets the set.union method fails the base case:
>
> >>> sets = []
> >>> set.union(*sets)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: descriptor 'union' of 'set' object needs an argument
>
> In the case of intersection perhaps the base case should be undefined.
>

Rather than calling the unbound method, why not just call it on an
empty set? That defines your base case as well.

set().union(*sets)

ChrisA


More information about the Python-list mailing list