KatInterview

Build a Function Pipeline and JSON Serialization Mixin

Data Structure DesignModel answer
HardModel answerData Structure Designpythonclosuresmetaprogramming

Last updated

Create a left-to-right function compositor and a mixin class that serializes object attributes to JSON with configurable privacy filtering.

You're developing utilities for a data processing framework. Build two independent components:

Part 1: Function Pipeline Constructor

Write a function compose_pipeline(*funcs) that creates a new function executing a sequence of transformations left-to-right.

The returned function should:

  • Accept any positional and keyword arguments
  • Feed all arguments into the first function in the sequence
  • Pass each function's output as the single positional argument to the next function
  • Return an identity function (returns its input unchanged) when given no functions

Part 2: JSON Serialization Mixin

Design a JsonMixin class providing JSON serialization capability to any class that inherits from it.

Requirements:

  • Add a to_json(self, include_private=False) method
  • Convert all instance attributes to a JSON string
  • When include_private is False, skip attributes whose names begin with underscore
  • For values that cannot be JSON-encoded (functions, custom objects, etc.), substitute the string "[Unserializable]" for that specific value
  • If the entire structure cannot be serialized (circular references, invalid dict keys), return the string "[Unserializable]"

Examples

# Pipeline
def add_ten(x): 
    return x + 10
def double(x): 
    return x * 2

pipe = compose_pipeline(add_ten, double)
print(pipe(3))  # (3 + 10) * 2 = 26

# Serialization
class Record(JsonMixin):
    def __init__(self, value, internal):
        self.value = value
        self._internal = internal

r = Record(42, "confidential")
print(r.to_json())  # {"value": 42}
print(r.to_json(include_private=True))  # {"value": 42, "_internal": "confidential"}

Constraints

  • Only the first function receives the original arguments; subsequent functions always receive one argument
  • Use Python's json.dumps for the final encoding step
  • Handle edge cases gracefully without crashing

Hints

Hint 1

For the pipeline: capture the function sequence in a closure and distinguish between the empty case and the non-empty case

Hint 2

For serialization: inspect instance attributes with vars(self) and build a filtered dictionary before encoding

Hint 3

Use the default parameter of json.dumps to handle individual non-serializable values, and wrap the entire call to catch structural encoding failures