Python Dataclasses
Apply your skills with a real-world coding challenge. Try to solve it yourself first!
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
- Test Case 1 (Valid User Creation):
- Input:
User(name="Alice", age=28, api_token="secret_abc") -
Expected Output: A successfully created
Userobject using an emptydownloadslist. -
Test Case 2 (Validation Failure on Bad API Data):
- Input:
User(name="Bob", age=-5, api_token="secret_xyz") -
Expected Behavior: The program should catch the invalid age during the post-initialization phase and raise a
ValueError. -
Test Case 3 (Parallel Immutability Check):
- Input:
user = User(name="Charlie", age=30, api_token="token_123")followed by an attempt to assignuser.age = 31. -
Expected Behavior: Python should aggressively block the assignment and raise a
FrozenInstanceError(or similar attribute error), proving an object is simply safely immutable. -
Test Case 4 (Isolated Default Lists):
- Input: Create
user1 = User(...)anduser2 = User(...). Append "file_A.txt" touser1.downloads. - Expected Behavior:
user2.downloadsshould remain completely empty, proving no shared state bugs exist.
Verify Your Solution
Write your solution in the compiler, run it to verify output, then click below to verify.