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

Chris Angelico rosuav at gmail.com
Fri Sep 24 21:14:08 EDT 2021


On Sat, Sep 25, 2021 at 11:11 AM Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> On Sat, 25 Sept 2021 at 02:01, Chris Angelico <rosuav at gmail.com> wrote:
>>
>> 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:
>> > > 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)
>
>
> That is indeed what I do but it seems unnatural compared to simply union(*sets). It shouldn't be necessary to create a redundant empty set just to compute the union of some other sets. If there was a union function then I don't think I would ever use the union method.
>

Maybe, but if you start with a set, then you define the base case, and
it also is quite happy to take non-set arguments:

>>> set().union([1,2,3], map(int, "234"), {3:"three",4:"four",5:"five"})
{1, 2, 3, 4, 5}

ChrisA


More information about the Python-list mailing list