Safe Lookups

Step 3: Safe Lookups

Real config code asks for keys that may not be set, and wants a fallback rather than a crash or a bare None it has to check. It also wants a clean way to test for presence.

Extend the registry:

  • get now takes an optional default. Return the value for key, or default when key is absent. When no default is passed, missing keys return None.
  • has returns True when key is present, else False.

These small conveniences are what turn a raw dict into a friendly registry API.

Hints
Starter code
class Config:
    _instance = None

    def __init__(self):
        self._data = {}

    @classmethod
    def instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    @classmethod
    def reset(cls):
        cls._instance = None

    def set(self, key, value):
        self._data[key] = value

    def get(self, key, default=None):
        """Return the value for key, or default when key is absent."""
        # TODO
        pass

    def has(self, key):
        """Return True if key is present, else False."""
        # TODO
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.