Skip to content

Instantly share code, notes, and snippets.

@LemonPi
Last active November 9, 2016 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LemonPi/fbc4a41a28cd349c7a3f18ea8a1bd6f1 to your computer and use it in GitHub Desktop.
Save LemonPi/fbc4a41a28cd349c7a3f18ea8a1bd6f1 to your computer and use it in GitHub Desktop.
python dictionary with restricted key type, given at compile time
# -*- coding: utf-8 -*-
class TypedDict(dict):
"""Dictionary with keys restricted to a specific type, given at creation time"""
def __init__(self, key_type):
print("initializing with", key_type)
self.key_type = key_type
def __getstate__(self):
return self.key_type, dict(self)
def __setstate__(self, state):
self.key_type, data = state
self.update(data)
def __reduce__(self):
# need custom reduce to bypass dict's special deserialization protocol
return TypedDict, (self.key_type,), self.__getstate__()
def __setitem__(self, key, value):
if isinstance(key, self.key_type):
return super(TypedDict, self).__setitem__(key, value)
raise KeyError(
"dictionary accepts only keys of type {} but given {}".format(self.key_type.__name__, type(key).__name__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment