mirror of
https://github.com/KevinMidboe/python-gpiozero.git
synced 2025-10-29 17:50:37 +00:00
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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user