Created
March 26, 2012 14:11
-
-
Save chobits/2205352 to your computer and use it in GitHub Desktop.
python: careful of swaping value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]