Extras · Practice

Quiz & exercises

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

Quiz

1. What does this print?
from types import MappingProxyType
d = {'a': 1}
mp = MappingProxyType(d)
d['b'] = 2
print(len(mp), mp.get('b'))
2. What does this print?
from types import MappingProxyType
mp = MappingProxyType({'a': 1})
try:
    mp['a'] = 2
except TypeError:
    print('TypeError', end=' ')
print(hasattr(mp, 'update'))
3. What does this print?
from types import MappingProxyType
mp = MappingProxyType({'tags': ['a']})
mp['tags'].append('b')
print(mp['tags'])
4. What does this print?
from types import MappingProxyType
mp = MappingProxyType({'a': 1})
c = mp.copy()
c['a'] = 99
print(type(c).__name__, mp['a'])
5. Why is a class's __dict__ a mappingproxy instead of a plain dict?

Coding exercises

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

Exercise 1: A read-only view of internal state

Write a class Inventory that keeps item counts in a private dict.

- add(item, qty=1) increases the count of item (qty must be positive, otherwise raise ValueError). - remove(item, qty=1) decreases it, deleting the item when it reaches 0. Removing more than is in stock raises ValueError. - The property stock returns a read-only, live view of the counts: callers can read it, but any attempt to assign to it raises TypeError, and it always reflects later changes.

Hints (2)
  1. Wrap the private dict once with types.MappingProxyType and return that proxy from the property; it stays in sync automatically.
  2. Validate before changing anything, so a failed remove leaves the stock untouched.
Show a solution
from types import MappingProxyType

class Inventory:
    def __init__(self):
        self._stock = {}
        self._view = MappingProxyType(self._stock)

    def add(self, item, qty=1):
        if qty <= 0:
            raise ValueError('qty must be positive')
        self._stock[item] = self._stock.get(item, 0) + qty

    def remove(self, item, qty=1):
        if qty <= 0:
            raise ValueError('qty must be positive')
        available = self._stock.get(item, 0)
        if qty > available:
            raise ValueError(f'only {available} {item!r} in stock')
        if qty == available:
            del self._stock[item]
        else:
            self._stock[item] = available - qty

    @property
    def stock(self):
        return self._view

Exercise 2: Freeze a nested structure

A MappingProxyType is only read-only at the top level. Write deep_freeze(obj) that returns a fully read-only version of a nested structure:

- every dict becomes a MappingProxyType over a new dict whose values are frozen too, - every list becomes a tuple of frozen items, - every set becomes a frozenset, - anything else is returned unchanged.

The original object must not be modified.

Hints (2)
  1. Recurse: for a dict, build {k: deep_freeze(v) for k, v in obj.items()} and wrap that new dict in a proxy.
  2. Set elements are already hashable (and so immutable enough), so frozenset(obj) is all a set needs.
Show a solution
from types import MappingProxyType

def deep_freeze(obj):
    if isinstance(obj, dict):
        return MappingProxyType({k: deep_freeze(v) for k, v in obj.items()})
    if isinstance(obj, list):
        return tuple(deep_freeze(v) for v in obj)
    if isinstance(obj, set):
        return frozenset(obj)
    return obj