Skip to content

Instantly share code, notes, and snippets.

@MSeifert04
Created December 23, 2015 02:04
Show Gist options
  • Save MSeifert04/23f49c59bc29c79d5453 to your computer and use it in GitHub Desktop.
Save MSeifert04/23f49c59bc29c79d5453 to your computer and use it in GitHub Desktop.
Using dynamically generated subclasses.
class MetaMixinBase(object):
# This will be overwritten by the type-creator
_base = 'test'
def propagate_add(self, other, kw):
'''
Empty for now but later this might contain the propagation of meta in addition.
'''
self._propagate_possible(other)
return None
def _propagate_possible(self, other):
'''
Verify if the two metas are allowed to be combined.
'''
if self._base != other._base:
raise TypeError('Cannot propagate {0} with {1}'.format(self._base.__name__, other._base.__name__))
class MetaMixinCustom(MetaMixinBase):
def propagate_add(self, other, kw):
'''
Create a copy of the meta and then replace the new ones.
'''
self._propagate_possible(other)
ret = self._base(self)
ret[kw] = self[kw] + other[kw]
return ret
class NDDataOnlyMeta(object):
'''
Just very simulation of NDData with only data and meta just to verify it's working.
'''
def __init__(self, data, meta=None):
self.data = data
# Since we always have a dict I can skip the None-cases later on. :-)
if meta is None:
meta=OrderedDict()
# Create a dynamically generated meta subclass
meta = type('WithMixin',
(MetaMixinCustom, meta.__class__),
{'_base': meta.__class__})(meta)
# Save it
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)
# 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