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

Tony Meyer t-meyer at ihug.co.nz
Fri Mar 18 06:28:20 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.
>         """
>         try:
>             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()]
> But the dict.pop method is about 12 times faster. Is this worth doing?

The 2.4 builtin set's discard function looks like it does roughly the same
as the 2.3 sets.Set.  Have you tried comparing a C version of your version
with the 2.4 set to see if there are speedups there, too?

IMO keeping the sets.Set version as clean and readable as possible is nice,
since the reason this exists is for other implementations (Jython, PyPy,
...) and documentation, right?  OTOH, speeding up the CPython implementation
is nice and it's read by many fewer people.


More information about the Python-Dev mailing list