Coding Exercises · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Why does the encoder check isinstance(obj, datetime) before isinstance(obj, date)?
2. What does this print?
import json
from decimal import Decimal

price = Decimal('337.60')
as_float = json.loads(json.dumps(float(price)))
as_text = Decimal(json.loads(json.dumps(str(price))))
print(as_float, as_text)
3. What does this print?
class Stock:
    def __init__(self, symbol):
        self.symbol = symbol

print(Stock('TSLA') == Stock('TSLA'), [Stock('A')] == [Stock('A')])
4. The encoder returns obj.as_dict() for a Stock, and that dict still contains a date and several Decimals. What happens?
5. What does this print?
import json

def hook(d):
    return d.get('object', d)

text = '{"a": {"object": "Stock"}, "b": [{"object": "Trade"}, {"x": 1}]}'
print(json.loads(text, object_hook=hook))
6. In the marshmallow solution, why does make_stock contain data['open_'] = data.pop('open')?
7. Why does the marshmallow version not need an "object": "Stock" marker in the JSON?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Exercise 1: encode stocks and trades

Complete CustomEncoder, a json.JSONEncoder subclass, so that json.dumps(activity, cls=CustomEncoder) works for any structure containing Stock and Trade objects.

- A Stock or Trade becomes a JSON object with all its fields (as_dict()) plus a key "object" whose value is the class name ("Stock" or "Trade"). - A datetime becomes its ISO string, e.g. "2018-11-22T10:05:12". - A date becomes its ISO string, e.g. "2018-11-22". - A Decimal becomes a string with the exact digits, e.g. "337.60". - Anything else unsupported must still raise TypeError.

The classes are given; don't change them.

Hints (3)
  1. Whatever default returns is encoded recursively, so the dict from as_dict() may still contain dates and Decimals: add a branch for each value type.
  2. type(obj).__name__ gives 'Stock' or 'Trade'.
  3. str(Decimal('337.60')) is '337.60'; going through float would lose the trailing zero.
Show a solution
import json
from datetime import date, datetime
from decimal import Decimal

class Stock:
    def __init__(self, symbol, date, open_, high, low, close, volume):
        self.symbol = symbol
        self.date = date
        self.open = open_
        self.high = high
        self.low = low
        self.close = close
        self.volume = volume

    def as_dict(self):
        return dict(symbol=self.symbol, date=self.date, open=self.open, high=self.high,
                    low=self.low, close=self.close, volume=self.volume)

class Trade:
    def __init__(self, symbol, timestamp, order, price, volume, commission):
        self.symbol = symbol
        self.timestamp = timestamp
        self.order = order
        self.price = price
        self.commission = commission
        self.volume = volume

    def as_dict(self):
        return dict(symbol=self.symbol, timestamp=self.timestamp, order=self.order,
                    price=self.price, volume=self.volume, commission=self.commission)

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (Stock, Trade)):
            result = obj.as_dict()
            result['object'] = type(obj).__name__
            return result
        if isinstance(obj, datetime):      # check before date: datetime is a subclass
            return obj.isoformat()
        if isinstance(obj, date):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)
        return super().default(obj)

Exercise 2: Exercise 2: decode them again

JSON produced by the Exercise 1 encoder marks stocks and trades with "object": "Stock" / "object": "Trade". Dates, timestamps and prices are ISO strings and decimal strings.

Write:

- decode_financials(d): given a dict, return a Stock or Trade built from it (with real date, datetime, Decimal and int values) if it carries one of those markers, otherwise return d unchanged; - load_activity(text): decode a JSON string, converting marked objects anywhere in the document.

The classes (with __eq__) are given.

Hints (3)
  1. date.fromisoformat, datetime.fromisoformat and Decimal(text) reverse the encoder's conversions exactly.
  2. Pass object_hook=decode_financials to json.loads: it's called for every JSON object at every depth.
  3. Use d.get('object') so dicts without a marker don't raise KeyError.
Show a solution
import json
from datetime import date, datetime
from decimal import Decimal

class Stock:
    def __init__(self, symbol, date, open_, high, low, close, volume):
        self.symbol = symbol
        self.date = date
        self.open = open_
        self.high = high
        self.low = low
        self.close = close
        self.volume = volume

    def __eq__(self, other):
        return type(other) is Stock and vars(self) == vars(other)

class Trade:
    def __init__(self, symbol, timestamp, order, price, volume, commission):
        self.symbol = symbol
        self.timestamp = timestamp
        self.order = order
        self.price = price
        self.commission = commission
        self.volume = volume

    def __eq__(self, other):
        return type(other) is Trade and vars(self) == vars(other)

def decode_stock(d):
    return Stock(d['symbol'], date.fromisoformat(d['date']),
                 Decimal(d['open']), Decimal(d['high']), Decimal(d['low']),
                 Decimal(d['close']), int(d['volume']))

def decode_trade(d):
    return Trade(d['symbol'], datetime.fromisoformat(d['timestamp']), d['order'],
                 Decimal(d['price']), int(d['volume']), Decimal(d['commission']))

DECODERS = {'Stock': decode_stock, 'Trade': decode_trade}

def decode_financials(d):
    decoder = DECODERS.get(d.get('object'))
    return decoder(d) if decoder else d

def load_activity(text):
    return json.loads(text, object_hook=decode_financials)

Exercise 3: Exercise 3: let the declarations be the schema

Schema libraries derive serialization from declared field types. Dataclasses declare their fields and types too, so we can do the same with the standard library.

Write two generic functions that work for any dataclass whose fields are annotated with str, int, date, datetime or Decimal:

- to_dict(obj): return a dict of JSON-native values: date/datetime as ISO strings, Decimal as a string, str and int unchanged. - from_dict(cls, data): build an instance of the dataclass cls, converting each value back according to the field's declared type. If a field is missing or data has keys that aren't fields, raise ValueError.

Use dataclasses.fields(cls); each field has .name and .type (the annotated class).

Hints (3)
  1. A table mapping each type to a pair of functions, {date: (date.isoformat, date.fromisoformat), ...}, keeps both functions short.
  2. fields(obj) works on instances as well as classes, and f.type is the annotation, e.g. Decimal.
  3. Compare {f.name for f in fields(cls)} with data.keys() to find missing and unexpected keys.
Show a solution
import json
from dataclasses import dataclass, fields
from datetime import date, datetime
from decimal import Decimal

@dataclass
class Stock:
    symbol: str
    date: date
    open: Decimal
    high: Decimal
    low: Decimal
    close: Decimal
    volume: int

@dataclass
class Trade:
    symbol: str
    timestamp: datetime
    order: str
    price: Decimal
    volume: int
    commission: Decimal

# field type -> (to native, from native)
CONVERTERS = {
    str: (str, str),
    int: (int, int),
    date: (date.isoformat, date.fromisoformat),
    datetime: (datetime.isoformat, datetime.fromisoformat),
    Decimal: (str, Decimal),
}

def to_dict(obj):
    return {f.name: CONVERTERS[f.type][0](getattr(obj, f.name)) for f in fields(obj)}

def from_dict(cls, data):
    names = {f.name for f in fields(cls)}
    missing, extra = names - data.keys(), data.keys() - names
    if missing or extra:
        raise ValueError(f'missing: {sorted(missing)}, unexpected: {sorted(extra)}')
    return cls(**{f.name: CONVERTERS[f.type][1](data[f.name]) for f in fields(cls)})