Created
December 23, 2015 02:28
-
-
Save MSeifert04/a49cf43867b4048a6c7f to your computer and use it in GitHub Desktop.
Using invisible wrapper
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__)) | |
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 | |
@property | |
def meta(self): | |
return self._meta.data | |
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) | |
# 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