Created
December 23, 2015 02:26
-
-
Save MSeifert04/ad573f317424068a6e55 to your computer and use it in GitHub Desktop.
Using wrapper implementing getter/setter
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
class MetaWrapperBase(object): | |
def __init__(self, data): | |
self.data = data | |
def propagate_add(self, other, kw): | |
self._propagate_possible(other) | |
return None | |
def _propagate_possible(self, other): | |
if self.data.__class__.__name__ != other.data.__class__.__name__: | |
raise TypeError('Cannot propagate {0} with {1}'.format(self.data.__class__.__name__, | |
other.data.__class__.__name__)) | |
def __getitem__(self, item): | |
return self.data[item] | |
def __setitem__(self, item, value): | |
self.data[item] = value | |
class MetaWrapperCustom(MetaWrapperBase): | |
def propagate_add(self, other, kw): | |
self._propagate_possible(other) | |
ret = self.data.__class__(self.data) | |
ret[kw] = self.data[kw] + other.data[kw] | |
return ret | |
class NDDataOnlyMeta(object): | |
def __init__(self, data, meta=None): | |
self.data = data | |
if meta is None: | |
meta=OrderedDict() | |
# Create a dynamically generated meta subclass | |
meta = MetaWrapperCustom(meta) | |
self.meta = meta | |
def add(self, other, kw): | |
return self.__class__(self.data+other.data, meta=self.meta.propagate_add(other.meta, kw)) | |
# Showcase | |
from collections import OrderedDict | |
meta1 = {'a': 1, 'd': 2} | |
meta2 = OrderedDict({'c': 3, 'd': 4}) | |
meta3 = {'c': 3, 'd': 4} | |
# Same type of meta: Should work | |
nd1 = NDDataOnlyMeta(5, meta=meta1) | |
nd2 = NDDataOnlyMeta(10, meta=meta3) | |
nd3 = nd1.add(nd2, 'd') | |
print(nd3.meta.data) | |
# Different types of meta: Shouldn't work | |
nd1 = NDDataOnlyMeta(5, meta=meta1) | |
nd2 = NDDataOnlyMeta(10, meta=meta2) | |
try: | |
nd3 = nd1.add(nd2, 'd') | |
except TypeError: | |
print("Should't work") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment