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

Chris Angelico rosuav at gmail.com
Fri Sep 24 09:53:00 EDT 2021


On Fri, Sep 24, 2021 at 11:47 PM Steve Keller <keller.steve at gmx.de> wrote:
>
> Why do some built-in Python functions feel so differently:
>
> For example sum(), all(), any() expect exactly one argument which is a
> sequence to operate on, i.e. a list, an iterator or a generator etc.
>
>     sum([1,2,3,4])
>     sum(range(1, 101))
>     sum(2**i for i in range(10))
>     all([True, False])
>     any(even, {1,2,3,4})
>
> while other functions like set.union() and set.intersection() work on
> a list of arguments but not on a sequence:
>
>     set.intersection({1,2,3}, {3,4,5})
>
> but
>
>     set.union(map(...))           # does not work
>     set.intersection(list(...))   # does not work
>
> and you have to use a * instead
>
>     set.union(*map(...))
>
> etc.
>
> Is this just for historical reason?  And wouldn't it be possible and
> desirable to have more consistency?
>

The ones you're calling off the set class are actually meant to be methods.

>>> s = {1,2,3}
>>> s.intersection({3,4,5})
{3}

They expect a set, specifically, as the first argument, because
normally that one goes before the dot. If you want to call the unbound
method with two arguments, that's fine, but it's not the intended use,
so you have to basically fudge it to look like a normal method call :)
That's why it doesn't take a sequence.

ChrisA


More information about the Python-list mailing list