Skip to content

Instantly share code, notes, and snippets.

@ewdurbin
Last active February 17, 2018 00:29
Show Gist options
  • Save ewdurbin/279eefb44c6505a890213b7ec6240c26 to your computer and use it in GitHub Desktop.
Save ewdurbin/279eefb44c6505a890213b7ec6240c26 to your computer and use it in GitHub Desktop.
Twitter-Pollin

Twitter Poll...

I was doing some pair programming with someone with a different background and we were implementing a dict like class for on disk storage of key value pairs.

We reached a point where we had a discussion over the difference between the following implementations:

UPDATE: Note that the question is which method should call which :) It is toy code, written in minutes, without tests. Focus on the differences between the implementations and their flows, not edge cases and bugs.

Option A:

#!/usr/bin/env python3.6
  
import os

from urllib.parse import quote


class DiskStorage:

    def __init__(self, directory="storage"):
        self.directory = directory
        os.makedirs(directory, exist_ok=True)

    def __setitem__(self, key, value):
        key_path = os.path.join(self.directory, quote(key, safe=''))
        with open(key_path, 'w') as key_file:
            key_file.write(value)

    def __getitem__(self, key):
        key_path = os.path.join(self.directory, quote(key, safe=''))
        try:
            with open(key_path, 'r') as key_file:
                value = key_file.read()
        except FileNotFoundError:
            raise KeyError

    def get(self, key, default=None):
        try:
            return self.__getitem__(key)
        except KeyError:
            return default

Option B:

#!/usr/bin/env python3.6
  
import os

from urllib.parse import quote


class DiskStorage:

    def __init__(self, directory="storage"):
        self.directory = directory
        os.makedirs(directory, exist_ok=True)

    def __setitem__(self, key, value):
        key_path = os.path.join(self.directory, quote(key, safe=''))
        with open(key_path, 'w') as key_file:
            key_file.write(value)

    def __getitem__(self, key):
        value = self.get(key)
        if value is None:
            raise KeyError

    def get(self, key, default=None):
        key_path = os.path.join(self.directory, quote(key, safe=''))
        try:
            with open(key_path, 'r') as key_file:
                value = key_file.read()
        except FileNotFoundError:
            return default
        return value

So which do you prefer... and why?

Answer the poll and reply with commentary :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment