31. An Abstract Connector Class
Difficulty: Medium · Topic: OOP & classes
Pipelines talk to many storage systems through one interface. Write:
Connector, an abstract base class with abstract methodsread(key)andwrite(key, value), and a concrete methodcopy(key, other, new_key=None)that readskeyhere, writes it to the connectorotherundernew_key(default: the same key) and returns the key it wrote. Creating aConnector, or a subclass that misses an abstract method, raisesTypeError.S3Connector(bucket): stores values in a dictself.objectsunder"bucket/key". Reading a missing key raisesKeyError.DbConnector(table): stores values in a dictself.rowsunder the key. Rows must be dicts: writing anything else raisesTypeError.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
s3 = S3Connector('raw')
db = DbConnector('orders')
s3.write('o1.json', {'id': 1, 'amount': 30})
written = s3.copy('o1.json', db, new_key='o1')
(written, db.rows, s3.objects)Expected: ('o1', {'o1': {'id': 1, 'amount': 30}}, {'raw/o1.json': {'id': 1, 'amount': 30}})
Hints
Hint 1
Inherit fromabc.ABC and mark methods with @abstractmethod; Python then refuses to instantiate the class until every abstract method is implemented.Hint 2
Concrete methods in the base class can call the abstract ones: each subclass supplies its own version.Hint 3
isinstance(value, dict) checks the row type.Learn the concepts
- Classes, properties and dataclasses · 4 min read. Invariants, validated and read-only attributes, alternate constructors and record types.
- Dunder methods and abstract classes · 7 min read. Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.
More Python problems
- Bank Account with Validation · Easy
- Temperature with Properties · Easy
- Build Records from CSV Rows · Medium
- A Comparable Version Class · Medium
- LRU Cache · Hard
- A Transaction Context Manager · Hard