Skip to content

Instantly share code, notes, and snippets.

@fwiffo
Created March 26, 2013 21:51
Show Gist options
  • Save fwiffo/5249636 to your computer and use it in GitHub Desktop.
Save fwiffo/5249636 to your computer and use it in GitHub Desktop.
Using tuples to swap values around is a convenient, idiomatic and efficient way to avoid temporary variables. However, you have to be careful about the order in which you unpack a tuple! Don't think of them as "a bunch of assignments that happen at once" but rather a sequence of assignments that happen in order. I got bit by this today and it wa…
# Let's rearrange the hierarchy of these objects
foo = SomeClass()
foo.bar = SomeClass()
foo.bar.baz = None
assert foo.bar is not None # Fine so far...
new_foo, foo.bar, foo.bar.baz = foo.bar, foo.bar.baz, foo
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'NoneType' object has no attribute 'baz'
# Wait a sec, didn't we just assert that foo.bar is not None?
# Let's try that again...
foo = SomeClass()
foo.bar = SomeClass()
foo.bar.baz = None
# But let's reverse the order of the tuples
foo.bar.baz, foo.bar, new_foo = foo, foo.bar.baz, foo.bar
# That works fine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment