Skip to content

Instantly share code, notes, and snippets.

@sethwoodworth
Created August 11, 2013 02:30
Show Gist options
  • Save sethwoodworth/6203130 to your computer and use it in GitHub Desktop.
Save sethwoodworth/6203130 to your computer and use it in GitHub Desktop.
python 2.7 sets.Set update based on iterable method
def _update(self, iterable):
# The main loop for update() and the subclass __init__() methods.
data = self._data
# Use the fast update() method when a dictionary is available.
if isinstance(iterable, BaseSet):
data.update(iterable._data)
return
value = True
if type(iterable) in (list, tuple, xrange):
# Optimized: we know that __iter__() and next() can't
# raise TypeError, so we can move 'try:' out of the loop.
it = iter(iterable)
while True:
try:
for element in it:
data[element] = value
return
except TypeError:
transform = getattr(element, "__as_immutable__", None)
if transform is None:
raise # re-raise the TypeError exception we caught
data[transform()] = value
else:
# Safe: only catch TypeError where intended
for element in iterable:
try:
data[element] = value
except TypeError:
transform = getattr(element, "__as_immutable__", None)
if transform is None:
raise # re-raise the TypeError exception we caught
data[transform()] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment