Last active
November 9, 2016 10:39
-
-
Save LemonPi/fbc4a41a28cd349c7a3f18ea8a1bd6f1 to your computer and use it in GitHub Desktop.
python dictionary with restricted key type, given at compile time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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