A new to Python question

Steven Bethard steven.bethard at gmail.com
Sat May 14 18:14:57 EDT 2005


M.E.Farmer wrote:
>>They're both an UNPACK_SEQUENCE byte-code.
> 
> I have dissed it myself ;)
> My argument, if you can call it that, is that it is not clear that
> Python is going to do a tuple unpacking here or not !

Hmm...  Well, I wouldn't say that.  I think it's quite clear that 
Python's doing a tuple unpacking.  Just like it always does anytime 
there's a comma on the left-hand side of an assignment statement.

Note that there's nothing that forces you to write the unpack sequence 
like a tuple display.  You can write it like a list display too, and 
Python will treat it identically:

py> def unpack_tuple(t):
...     [x, y] = t
...
py> dis.dis(unpack_tuple)
   2           0 LOAD_FAST                0 (t)
               3 UNPACK_SEQUENCE          2
               6 STORE_FAST               2 (x)
               9 STORE_FAST               1 (y)
              12 LOAD_CONST               0 (None)
              15 RETURN_VALUE

I don't know how UNPACK_SEQUENCE is implemented, but at least on the 
Python level, no tuple or list is created in the unpacking process.

> Seems weird, non-intuitive that a tuple unpacking and tuple creation
> have the same bytecode.

Sorry, I don't understand.  Why do you think this?

py> def create_tuple(x, y):
...     (x, y)
...
py> dis.dis(create_tuple)
   2           0 LOAD_FAST                0 (x)
               3 LOAD_FAST                1 (y)
               6 BUILD_TUPLE              2
               9 POP_TOP
              10 LOAD_CONST               0 (None)
              13 RETURN_VALUE
py> def unpack_tuple(t):
...     x, y = t
...
py> dis.dis(unpack_tuple)
   2           0 LOAD_FAST                0 (t)
               3 UNPACK_SEQUENCE          2
               6 STORE_FAST               2 (x)
               9 STORE_FAST               1 (y)
              12 LOAD_CONST               0 (None)
              15 RETURN_VALUE

To me, it looks like tuple creation uses the BUILD_TUPLE op-code, and 
tuple unpacking uses the UNPACK_SEQUENCE op-code.  Could you explain 
what you meant by "a tuple unpacking and tuple creation have the same 
bytecode"?

STeVe



More information about the Python-list mailing list