Make CompositeDevice._named a frozendict (and add frozendict to compat.py)

This prevents it being modified post-construction (just like the way
CompositeDevice._all and CompositeDevice._order are already 'frozen' by being
tuples)
This commit is contained in:
Andrew Scheller
2016-05-31 16:52:14 +01:00
parent b3035d306e
commit 5455034a12
2 changed files with 34 additions and 3 deletions

View File

@@ -9,6 +9,9 @@ from __future__ import (
str = type('')
import cmath
import collections
import operator
import functools
# Back-ported from python 3.5; see
@@ -51,3 +54,30 @@ def median(data):
i = n // 2
return (data[i - 1] + data[i]) / 2
# Copied from the MIT-licensed https://github.com/slezica/python-frozendict
class frozendict(collections.Mapping):
def __init__(self, *args, **kwargs):
self.__dict = dict(*args, **kwargs)
self.__hash = None
def __getitem__(self, key):
return self.__dict[key]
def copy(self, **add_or_replace):
return frozendict(self, **add_or_replace)
def __iter__(self):
return iter(self.__dict)
def __len__(self):
return len(self.__dict)
def __repr__(self):
return '<frozendict %s>' % repr(self.__dict)
def __hash__(self):
if self.__hash is None:
hashes = map(hash, self.items())
self.__hash = functools.reduce(operator.xor, hashes, 0)
return self.__hash