[Python-Dev] Faster Set.discard() method?

Andrew McNamara andrewm at object-craft.com.au
Fri Mar 18 06:11:53 CET 2005

To avoid the exception in the discard method, it could be implemented as:

    def discard(self, element):
        """Remove an element from a set if it is a member.

        If the element is not a member, do nothing.
            self._data.pop(element, None)
        except TypeError:
            transform = getattr(element, "__as_temporarily_immutable__", None)
            if transform is None:
                raise # re-raise the TypeError exception we caught
            del self._data[transform()]

Currently, it's implemented as the much clearer:

        except KeyError:

But the dict.pop method is about 12 times faster. Is this worth doing?

Andrew McNamara, Senior Developer, Object Craft

More information about the Python-Dev mailing list