Skip to content

Instantly share code, notes, and snippets.

@chobits
Created March 26, 2012 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chobits/2205352 to your computer and use it in GitHub Desktop.
Save chobits/2205352 to your computer and use it in GitHub Desktop.
python: careful of swaping value
>>> class A():
... val = 0
...
>>> a = A()
>>> a.val, a = 1, a.val # right
>>> a = A()
>>> a, a.val = a.val, 1 # wrong
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'val'
>>> from dis import dis
>>> def swap(): # swap internal
... a, b = c, d
...
>>> dis(swap)
2 0 LOAD_GLOBAL 0 (c)
3 LOAD_GLOBAL 1 (d)
6 ROT_TWO
7 STORE_FAST 0 (a)
10 STORE_FAST 1 (b)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
@chobits
Copy link
Author

chobits commented Mar 26, 2012

What does a, b = c, d do?

stack[top] = c
stack[top+1] = d
a = stack[top]
b = stack[top+1]

what does wrong swap a, a.val = a.val, 1 do?

stack[top] = a.val
stack[top+1] = 1
a = stack[top] <-- Note: a is integer value 1
a.val = stack[top+1] <-- Error: a.val raise "AttributeError: 'int' object has no attribute 'val'"

opcode ROT_TWO will swap stack[top] with stack[top+1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment