Python multiprocessing Manager().dict(): Why Appends to Nested Lists Don't Show Up in Other Processes

TechLab Editorial TeamPublished 73 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

A common pattern for collecting results from multiprocessing workers is a shared multiprocessing.Manager().dict(). Each worker reports its status into the dictionary, and the main process reads it at the end.

The Specific Problem

Each key in the managed dictionary is a job ID, and its value is a list of status updates for that job (shared_data['job_X'] = [{'step': 1, ...}, ...]). Workers append new status entries to their job's list.

The appends are not visible to the main process or other workers unless the whole modified list is assigned back to the key. Prints inside the worker show the list growing, but the managed dictionary never changes.

Applies to all current Python 3 versions, using only the standard library.

Code Example

Python
import multiprocessing
import time
import os

def worker_task(worker_id, shared_data):
    pid = os.getpid()
    print(f"Worker {worker_id} (PID: {pid}) started.")
    job_key = f"job_status_{worker_id}"

    # Retrieve the list for modification.
    # Assume shared_data[job_key] was pre-initialized to an empty Python list.
    status_list = shared_data[job_key] # This gets a local copy of the list

    # Simulate some work and append status updates
    for i in range(3):
        status = {"step": i + 1, "message": f"Worker {worker_id} - processing step {i+1}", "timestamp": time.time()}
        print(f"Worker {worker_id} (PID: {pid}) appending locally: {status}")
        status_list.append(status) # This modifies the *local* list
        time.sleep(0.1)

    print(f"Worker {worker_id} (PID: {pid}) finished. Final local status_list size: {len(status_list)}")
    # Checking the shared_data directly from the worker also shows no updates (unless re-assigned)
    print(f"Worker {worker_id} (PID: {pid}) reporting final shared_data[{job_key}] size: {len(shared_data.get(job_key, []))}")


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    shared_data = manager.dict()

    num_workers = 2
    processes = []

    # Pre-initialize shared_data[job_key] with an empty Python list for each worker
    # This ensures a list object is present to start with.
    for i in range(num_workers):
        shared_data[f"job_status_{i}"] = [] # Storing an empty Python list.

    print("Main process starting workers...")
    for i in range(num_workers):
        p = multiprocessing.Process(target=worker_task, args=(i, shared_data))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    print("\nAll workers finished. Main process checking shared data:")
    for key, value in shared_data.items():
        print(f"  Key: {key}, Value: {value}, Type: {type(value)}")
        if isinstance(value, list):
            print(f"    List length: {len(value)}")

    manager.shutdown()
    print("Manager shut down.")

Expected Behavior

For each job_key (e.g., job_status_0), the main process should see a list containing 3 status dictionaries, as each worker appends 3 items to its respective list. The len() of the lists in shared_data should consistently be 3 for each job.

Actual Behavior

When the main process checks shared_data after all workers are done, the lists associated with job_status_0 and job_status_1 are empty, or sometimes contain a single item if the initial assignment was handled differently, but none of the subsequent append() calls from the workers are reflected. The print statements inside the worker show status_list growing, but this growth isn't propagated to the manager.dict().

For example, the output shows:

Code
  Key: job_status_0, Value: [], Type: <class 'list'>
    List length: 0
  Key: job_status_1, Value: [], Type: <class 'list'>
    List length: 0

There are no errors or stack traces, just missing data.

The question: why don't the appends propagate, and what's the right way to share nested mutable data between processes?

Advertisement

1 Answer

0

The behaviour comes from how Manager objects work: they serialize values, keep them in a separate server process, and give you proxies or copies depending on what you stored.

The Root Cause: Serialization and Proxying of Mutable Objects

When you store a standard Python mutable object (like a list or dict) as a value in a multiprocessing.Manager().dict(), the Manager doesn't magically make that exact object's memory accessible to other processes. Instead, the Manager runs a separate server process that holds the actual shared data. When you shared_data[key] = some_value, some_value is serialized, sent to the manager's server process, and stored there.

Conversely, when you retrieved_value = shared_data[key], the manager's server process deserializes a copy of the value (or creates a proxy for it, depending on the object type and context) and sends it back to your worker process. For standard Python lists and dictionaries stored as values within a Manager().dict(), you typically get a local, independent copy of that object.

In the code above:

  1. shared_data[job_key] = [] in the if __name__ == "__main__": block serializes an empty Python list and sends it to the Manager server. The Manager server stores this empty list.
  2. Inside worker_task, when you call status_list = shared_data[job_key], the Manager server serializes its stored list (which is empty), sends it to the worker, and the worker deserializes it into a new, local Python list object. status_list is now a completely separate list in the worker's memory space.
  3. When you call status_list.append(status), you are modifying this local copy within the worker's process. These changes are never communicated back to the Manager server because you haven't performed an operation that would trigger serialization and an update on the managed dictionary (i.e., you haven't assigned a new value to shared_data[job_key]). The Manager only detects changes when an entire key's value is replaced.

This behavior is fundamentally different from threading, where all threads share the same memory space, and direct mutations to a shared object are immediately visible.

Corrected Code: Explicit Re-assignment

The fix is to explicitly re-assign the entire modified list back to the manager.dict() key after you've made your changes. This tells the Manager to serialize the new state of the list and update its internal storage.

Python
import multiprocessing
import time
import os

def worker_task_corrected(worker_id, shared_data):
    pid = os.getpid()
    print(f"Worker {worker_id} (PID: {pid}) started.")
    job_key = f"job_status_{worker_id}"

    # 1. Retrieve the current list from the managed dictionary.
    #    This gets a *local copy* of the Python list stored on the Manager server.
    current_status_list = shared_data[job_key] 

    # Simulate some work and append status updates
    for i in range(3):
        status = {"step": i + 1, "message": f"Worker {worker_id} - processing step {i+1}", "timestamp": time.time()}
        print(f"Worker {worker_id} (PID: {pid}) appending locally to copy: {status}")
        current_status_list.append(status) # This modifies the *local* list copy.
        time.sleep(0.1)

    # 2. To make the changes visible, the *entire modified local list*
    #    must be re-assigned back to the key in the managed dictionary.
    #    This triggers serialization and an update on the Manager's server process.
    shared_data[job_key] = current_status_list # <-- THE CRITICAL FIX

    print(f"Worker {worker_id} (PID: {pid}) finished. Final local status_list size: {len(current_status_list)}")
    # Verify by retrieving again. This will fetch the newly updated list from the manager.
    print(f"Worker {worker_id} (PID: {pid}) reporting final shared_data[{job_key}] size: {len(shared_data.get(job_key, []))}")


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    shared_data = manager.dict()

    num_workers = 2
    processes = []

    # Pre-initialize shared_data[job_key] with an empty Python list for each worker.
    for i in range(num_workers):
        shared_data[f"job_status_{i}"] = [] # Still storing empty Python lists.

    print("Main process starting workers...")
    for i in range(num_workers):
        p = multiprocessing.Process(target=worker_task_corrected, args=(i, shared_data))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

    print("\nAll workers finished. Main process checking shared data:")
    for key, value in shared_data.items():
        print(f"  Key: {key}, Value: {value}, Type: {type(value)}")
        if isinstance(value, list):
            print(f"    List length: {len(value)}")

    manager.shutdown()
    print("Manager shut down.")
  1. Performance Overhead: Frequent retrieval, modification, and re-assignment of large lists or dictionaries can introduce significant performance overhead. Each such operation involves serialization, inter-process communication, and deserialization. For very large or frequently updated structures, this can become a bottleneck.
  2. Race Conditions: Even with explicit re-assignment, if multiple processes try to retrieve, modify, and re-assign the same nested list concurrently (e.g., job_status_0), you can still encounter race conditions. One process's update might overwrite another's if they read the list at roughly the same time, modify their local copies, and then the re-assignments happen in an unfavorable order. For such scenarios, you'd need explicit locking (e.g., using manager.Lock()) around the read-modify-write cycle or consider a queue-based approach.

💡 Bonus Tip: Use Manager().list() for Truly Shared Mutable Sequences

If modifications like append() should be visible across processes without reassigning anything, store a managed list (manager.list(), or manager.dict() for nested dictionaries) as the value instead of a plain list. Nesting proxies inside other managed objects is supported since Python 3.6. These Manager specific data types provide proxy objects whose methods (like append, extend, pop, etc.) directly communicate with the server process to modify the shared data.

To implement this, you would initialize your shared_data like this:

Python
# In main process:
shared_data[f"job_status_{i}"] = manager.list() # Store a managed list, not a Python list

# In worker process:
status_list_proxy = shared_data[job_key] # This now gets a proxy object to the managed list
status_list_proxy.append(status) # This method call is proxied to the manager server and works directly!

This approach is more idiomatic for shared mutable collections, as it hides the underlying IPC and serialization details, making the code cleaner and less error-prone for direct mutations. However, be mindful of the performance implications of frequent operations on managed objects, as they still involve inter-process communication. For collecting results, a multiprocessing.Queue (each worker puts (job_id, status) tuples, the main process reads them) is usually simpler and faster than shared state: there's no read-modify-write and therefore nothing to lock. concurrent.futures.ProcessPoolExecutor goes one step further and just returns each worker's result.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.