Login Sign Up
Challenges / python dataclasses fields frozen slots 2024

python dataclasses fields frozen slots 2024 Challenge

Read the problem description and solve the challenge in the workspace.

Open Full Sandbox Studio
Problem Description

Coding Challenge: The High-Performance, Thread-Safe User API Pipeline

Problem Description Imagine you are building the backend for a massive data aggregation dashboard that processes millions with user profiles from a highly unreliable third-party API, while because of the enormous volume of data creating standard Python classes for each user is causing your computer's RAM towards choke due to the hidden dictionary (__dict__) attached to every object. Also you're using the multiprocessing architecture for process this data, meaning your objects must be completely thread-safe to prevent data corruption;

your task is to build a robust User object using Python Dataclasses that meets a following strict professional requirements: 1. Memory Optimized: It must abandon the standard dictionary structure and lock down the exact memory spaces needed. 2. Thread-Safe (Immutable): Once the user object is created, its data can never be changed by another process. 3. Safe Defaults: Every user must start with their own empty list of downloaded files. This list can't accidentally be shared across different users. 4. Data Validation: Because an API is unreliable, it sometimes sends users with negative ages (e.g., -5). You must implement custom validation immediately after the object is created to catch this and raise the ValueError.

Difficulty Level: Advanced

Input & Output Specifications * Input: * Raw data representing a user profile: name (string), age (integer), and api_token (string). * Output: * Returns a validated, memory-optimized frozen User dataclass instance. * Raises a ValueError if the age provided is less than 0. * Raises an error (e.g., FrozenInstanceError) if an external process attempts to modify the object after creation.

Starter Code Boilerplate

from dataclasses import dataclass, field

# TODO: Add the correct decorator arguments to ensure memory optimization and immutability
@dataclass
class User:
    name: str
    age: int
    api_token: str

    # TODO: Add a 'downloads' property that defaults to an empty list without sharing state across instances
    downloads: list = ... 

    # TODO: Implement the correct method to validate the age immediately after object creation
    def ...
        pass

Hints * High-Performance Memory: Use slots=True in your dataclass decorator to delete the fat, hidden __dict__ and significantly speed up attribute access. * Bulletproof Safety: Use frozen=True in your decorator to make a dataclass completely read-only, protecting it when passed around in parallel architectures. * Complex Defaults: Don't really use [] as the default value, or all users will share exact same list in memory! Use field(default_factory=list) to guarantee every user gets their own fresh, empty box. * Validating Data: Dataclasses automatically generate the __init__ method. To run custom safety checks upon age attribute after initialization implement a __post_init__ method.

Test Cases

  1. Test Case 1 (Valid User Creation):
  2. Input: User(name="Alice", age=28, api_token="secret_abc")
  3. Expected Output: A successfully created User object using an empty downloads list.

  4. Test Case 2 (Validation Failure on Bad API Data):

  5. Input: User(name="Bob", age=-5, api_token="secret_xyz")
  6. Expected Behavior: The program should catch the invalid age during the post-initialization phase and raise a ValueError.

  7. Test Case 3 (Parallel Immutability Check):

  8. Input: user = User(name="Charlie", age=30, api_token="token_123") followed by an attempt to assign user.age = 31.
  9. Expected Behavior: Python should aggressively block the assignment and raise a FrozenInstanceError (or similar attribute error), proving an object is simply safely immutable.

  10. Test Case 4 (Isolated Default Lists):

  11. Input: Create user1 = User(...) and user2 = User(...). Append "file_A.txt" to user1.downloads.
  12. Expected Behavior: user2.downloads should remain completely empty, proving no shared state bugs exist.

Loading sandbox workspace environment...

Verify Your Solution

Run assertions against your code in the sandbox environment.

Sandbox Instructions

1. Click Copy Starter Boilerplate at the top to copy function definition.
2. Use the interactive compiler to implement and run your code securely.
3. Click Verify & Submit Solution to validate your code.