[Python-ideas] universal set object for use in set manipulation

Jan Kanis jan.kanis at phil.uu.nl
Sat Jul 25 18:21:47 CEST 2009


Going back to the original problem...

On Thu, Jul 23, 2009 at 09:12, Andrew Bennetts<andrew at bemusement.org> wrote:
> Andy Kish wrote:
> [...]
>>
>> The above intersection case would end up looking something like:
>>
>>     set_intersection = set.universal()
>>     for s in sets:
>>         set_intersection &= s
>
> Or even:
>
>   set_intersection = reduce(operator.and_, sets, set.universal())
>
> Although, you can already pass multiple (or zero) sets to set.intersection().
> So your special case version can be a little simpler...
>
>   sets = list(sets)
>   if len(sets) == 0:
>       return set()
>   return sets[0].intersection(sets[1:])
>
> Which isn't as elegant, but it's also not so bad.

But set.intersection doesn't need to be called using dot notation, the
class attribute call works just as well:


  try:
      return set.intersection(*sets)
  except TypeError:
      return set()


I'd say this is as elegant as the OPs solution with the universal set.

Universal sets and other such cofinite sets could be nice, but I don't
think they should be in the python standard library.



More information about the Python-ideas mailing list