Build a Function Pipeline and JSON Serialization Mixin
Data Structure DesignModel answerLast 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_privateisFalse, 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.dumpsfor 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
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests your understanding of Python closures, argument forwarding, runtime introspection, and the JSON encoding protocol.
Approach: Function Pipeline
The pipeline constructor is a closure factory. It captures the function sequence and returns a new callable that chains them together.
Empty input case: When no functions are provided, return a simple identity function that echoes its input. Since we don't know what arguments will be passed, accept a single argument.
Non-empty case: Split the sequence into the first function and the remainder. The returned pipeline function:
- Calls the first function with all received
*argsand**kwargs - Threads the result through each remaining function as its sole positional argument
- Returns the final result
This implements left-to-right composition (pipeline order), not mathematical right-to-left composition. The execution order is f₁ → f₂ → f₃.
Why only the first function gets kwargs: Subsequent functions receive exactly one value—the previous result. Attempting to forward kwargs to all stages would fail for functions expecting a single argument.
Approach: JSON Mixin
A mixin provides reusable behavior without introducing its own state. This class adds serialization through inheritance.
Three-layer error handling:
-
Attribute filtering (pre-encoding): Use
vars(self)to access the instance dictionary. Build a new filtered dict excluding underscore-prefixed keys when privacy is requested. Never modify the original__dict__. -
Per-value fallback (during encoding): Supply a
defaultcallback tojson.dumps. When the encoder encounters a non-serializable type (function, custom class instance), it invokes this callback. Return"[Unserializable]"to substitute that specific value while preserving the rest of the structure. -
Structural failures (post-attempt): Some issues bypass the
defaulthook:- Circular references in containers trigger
ValueError - Non-string dictionary keys cause
TypeError - Excessive nesting could raise
RecursionError
Wrap the entire
json.dumpscall in a try-except block and return"[Unserializable]"for these catastrophic failures. - Circular references in containers trigger
Complexity Analysis
Pipeline:
- Construction: O(k) time and space for k functions
- Execution: O(k) function calls plus the time complexity of each function
- Memory: O(k) for the captured tuple
Serialization:
- Time: O(n) where n is the total size of the attribute graph
- Space: O(n) for the JSON string plus O(d) stack depth for circular reference tracking
- Python's encoder maintains an id set to detect cycles, preventing infinite recursion
Edge Cases and Pitfalls
Pipeline:
- Empty function list must return identity:
compose_pipeline()(5)→5 - Single function should behave identically to calling that function directly
- Keywords passed to the pipeline only reach the first function
- All intermediate values are ephemeral; only the final result is returned
Serialization:
- Object with only private attributes produces
"{}"when privacy filtering is enabled - Built-in containers (lists, dicts) holding non-serializable items are partially encoded:
{"data": [1, "[Unserializable]", 3]} - Self-referencing list like
x.items = []; x.items.append(x.items)returns"[Unserializable]"due to circularity - Class attributes (defined on the class, not the instance) are correctly excluded since they're not in
vars(self) - Objects using
__slots__lack__dict__—a limitation worth mentioning
Implementation
import json
from typing import Callable
def compose_pipeline(*funcs: Callable) -> Callable:
"""Create a left-to-right function pipeline. First function receives all
arguments; each subsequent function receives only the previous result."""
funcs = tuple(funcs) # Snapshot to prevent external mutation
if not funcs:
return lambda x: x
first_func, remaining = funcs[0], funcs[1:]
def pipeline(*args, **kwargs):
result = first_func(*args, **kwargs)
for func in remaining:
result = func(result)
return result
return pipeline
class JsonMixin:
"""Mixin providing JSON serialization of instance attributes."""
def to_json(self, include_private: bool = False) -> str:
# Build filtered attribute dictionary
attributes = {
k: v for k, v in vars(self).items()
if include_private or not k.startswith('_')
}
# Attempt serialization with per-value fallback
try:
return json.dumps(
attributes,
default=lambda _: "[Unserializable]",
check_circular=True
)
except (TypeError, ValueError, RecursionError):
# Structural encoding failures
return "[Unserializable]"
# Demonstration
if __name__ == "__main__":
# Pipeline tests
def add_ten(x):
return x + 10
def double(x):
return x * 2
pipe = compose_pipeline(add_ten, double)
print(pipe(3)) # 26
identity = compose_pipeline()
print(identity(7)) # 7
# Serialization tests
class Record(JsonMixin):
def __init__(self, value, internal):
self.value = value
self._internal = internal
r = Record(42, "secret")
print(r.to_json()) # {"value": 42}
print(r.to_json(include_private=True)) # {"value": 42, "_internal": "secret"}
# Non-serializable attribute
r.callback = lambda: None
print(r.to_json()) # {"value": 42, "callback": "[Unserializable]"}
# Circular reference
r.cycle = []
r.cycle.append(r.cycle)
print(r.to_json()) # [Unserializable]
Common Mistakes
- Forwarding kwargs through every stage: This breaks functions expecting exactly one argument. Only the first function should receive the original kwargs.
- Using reduce without proper initialization: Naive reduction loses access to the variadic arguments of the first call.
- Catching all exceptions at the outer level only: Without the
defaulthook, one bad attribute contaminates the entire output. Per-value substitution is more useful. - Mutating
self.__dict__directly: Filtering should create a new dictionary. Serialization must not have side effects. - Catching bare
Exception: This masks legitimate bugs. Catch only the specific exceptions you expect from JSON encoding.