Skip to content

Return NotImplemented for SortedSet.__and__ #219

Description

@SimpleArt

Binary operators such as __eq__, __and__, etc. should return NotImplemented in the event that the given argument is an unsupported type rather than raising an error. This allows the other object to patch in its own implementation.

Roughly speaking, it means code should be written like this:

from typing import Iterable


class SortedSet:

    def __and__(self, other):
        if isinstance(other, Iterable):  # Or `hasattr(type(other), "__iter__")`.
            return self.intersection(other)
        else:
            return NotImplemented  # `self & other` then checks `other.__and__(self)`.

This allows cases such as this:

class Interval:  # Not a set e.g. does not contain `__iter__`.

    def __and__(self, other):
        if isinstance(other, Interval):
            ...
        elif isinstance(other, Iterable):
            return {x for x in other if x in self}
        else:
            return NotImplemented

    def __contains__(self, other):
        ...


sorted_set & interval  # Expected set, got TypeError.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions