Make State class immutable

This commit is contained in:
Paulus Schoutsen
2016-02-09 23:27:01 -08:00
parent 70a528c04b
commit b0948bef5f
6 changed files with 10 additions and 29 deletions

View File

@@ -10,6 +10,7 @@ import time
import logging
import signal
import threading
from types import MappingProxyType
import enum
import functools as ft
from collections import namedtuple
@@ -353,7 +354,7 @@ class State(object):
self.entity_id = entity_id.lower()
self.state = state
self.attributes = attributes or {}
self.attributes = MappingProxyType(attributes or {})
self.last_updated = dt_util.strip_microseconds(
last_updated or dt_util.utcnow())
@@ -381,12 +382,6 @@ class State(object):
self.attributes.get(ATTR_FRIENDLY_NAME) or
self.object_id.replace('_', ' '))
def copy(self):
"""Return a copy of the state."""
return State(self.entity_id, self.state,
dict(self.attributes), self.last_changed,
self.last_updated)
def as_dict(self):
"""Return a dict representation of the State.
@@ -395,7 +390,7 @@ class State(object):
"""
return {'entity_id': self.entity_id,
'state': self.state,
'attributes': self.attributes,
'attributes': dict(self.attributes),
'last_changed': dt_util.datetime_to_str(self.last_changed),
'last_updated': dt_util.datetime_to_str(self.last_updated)}
@@ -459,14 +454,11 @@ class StateMachine(object):
def all(self):
"""Create a list of all states."""
with self._lock:
return [state.copy() for state in self._states.values()]
return list(self._states.values())
def get(self, entity_id):
"""Retrieve state of entity_id or None if not found."""
state = self._states.get(entity_id.lower())
# Make a copy so people won't mutate the state
return state.copy() if state else None
return self._states.get(entity_id.lower())
def is_state(self, entity_id, state):
"""Test if entity exists and is specified state."""