operators and datatypes for sets

Alex Martelli aleaxit at yahoo.com
Fri Apr 27 04:34:23 EDT 2001


"Anton Vredegoor" <anton at vredegoor.doge.nl> wrote in message
news:9cab20$lm8$1 at news.hccnet.nl...
    [snip]
> or the html version:
>
> http://home.hccnet.nl/a.vredegoor/universe/universe.html
>
> And let me know what you think about it.

Implementation issues aside (always a minor concern at
first:-), I do have one suggestion regarding the interface.

I think it would be handy for a 'set' operand to "coerce"
the other operand (if the latter is a sequence) to 'set',
much in the same spirit as, e.g., a complex number "coerces"
a float operand so you don't have to explicitly write

    (2.0+3.0j) + complex(x)

but simply

    (2.0+3.0j) + x

even if x refers to a float (or int...) at this point.


You can use the __coerce__ special method, or do it in
each operator (and its __rXXX__ version for completeness).

Also .has_subset.  Implementation is trivial, just a
small factory function that you might as well expose:

def make_set(set_or_sequence):
    if isinstance(set_or_sequence, set):
        return set_or_sequence
    else:
        return set(set_or_sequence)

and just call this appropriately on "other operand".

Sounder implementation migh be to accept classes to
you not-known that "implement a set interface" or
"are adaptable to a set protocol" rather than just
do isinstance(), but unless/until PEPs 245/246 or some
variants thereof should prevail, it's never very
sure how best to test... maybe here, since you're
always using other.vector, you could be satisfied
with testing for that with hasattr().


Alex






More information about the Python-list mailing list