Search code examples
pythonmultithreadingthread-safetyatomic

Is Python unpacking thread safe?


Is an operation like x,y = self.mytuple atomic in Python ?

Or could self.mytuple be modified by another thread during the assignment, leading to x refering to the first version of self.mytuple, and y to the second version?

I'm using Python 3.


Solution

  • It is thread-safe only if item access is not handled by Python code.

    The unpacking is handled by one bytecode:

    >>> def f():
    ...     a, b = self.mytuple
    ... 
    >>> import dis
    >>> dis.dis(f)
      2           0 LOAD_GLOBAL              0 (self) 
                  3 LOAD_ATTR                1 (mytuple) 
                  6 UNPACK_SEQUENCE          2 
                  9 STORE_FAST               0 (a) 
                 12 STORE_FAST               1 (b) 
                 15 LOAD_CONST               0 (None) 
                 18 RETURN_VALUE         
    

    Provided self.mytuple is really a standard Python tuple, that is threadsafe.

    As soon as accessing items from mytuple triggers a custom __getitem__, all bets are off.