Lifetime of variables created when assigning to something that looks like a tuple

There is this code:

>>> (a, b) = (2, 3)
>>> a
2
>>> b
3

Why variables a and b are alive after tuple creation? I mean that here:

(a, b) = (2, 3)

is created some tuple and this tuple is not assigned to any variable so garbage collector should immediately destroy this tuple after this line.

Variables a and b are only references by this tuple - so if this tuple (a, b) is destroyed then variables a and b should be only destroyed also.

So why these variables still exist after definition of tuple?

Answers


The parser doesn't see (a, b) as a tuple, although it does do tuple unpacking for you. Thus, there is no tuple to create, let alone destroy. Instead, python sees this as two separate variables a and b.

You can see this if you were to disassemble the compiled bytecode for the statement:

>>> import dis
>>> def foo():
...     (a, b) = (2, 3)
... 
>>> dis.dis(foo)
  2           0 LOAD_CONST               3 ((2, 3))
              3 UNPACK_SEQUENCE          2
              6 STORE_FAST               0 (a)
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        

The constant (2, 3) is unpacked, then stored into the local variables a and b.


(a, b) = (2, 3)

Does not create a tuple, but rather assigns two variables a and b.

It's equivalent to:

a,b = 2,3

and sets a=2 and b=3 "at the same time". This is useful, for example when switching variables:

a,b = b,a

which would set a=3 and b=2 (and would require a temporary variable if done in sequence).


Need Your Help

Implementing a database of people that have alternative names and linking all names together

sql database-design

I'm creating a database for a small museum of commemorative pieces. This are mostly made for royal events but there are other areas as well. Therefore, most pieces are related to a person and it sh...

Adding a border around selected day in Fullcalendar

css fullcalendar

I'm using FullCalender and would like to change the styling in my month and week views so that rather than a yellow shade for the selected day, there is instead a thick border around it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.