Skip to content

Instantly share code, notes, and snippets.

@derrandz
Last active May 27, 2016 19:09
Show Gist options
  • Save derrandz/5e72dfe1ab1fb2579b7bd48461119965 to your computer and use it in GitHub Desktop.
Save derrandz/5e72dfe1ab1fb2579b7bd48461119965 to your computer and use it in GitHub Desktop.
This is a class decorator for divergent classes, link to the definition of such term
"""
To understand what 'divergent' classes mean, please refer to the link: https://coderwall.com/p/hnaroq/divergent-classes-in-python
Nothing special, just I like to put fancy names on things from time to time ;)
Ofcourse, we can acheive the same thing using inheritence, but some of us design in a way that inheritence would not fit in,
This is the solution.
Besides, decorators are cool!
Signed, Hamza Ouaghad.
"""
def divergent(dvgpoint):
def class_rebuilder(cls):
class DivergentClass(cls):
_original_class = cls.__name__
_divergent = True
_divergence_point = dvgpoint
def __init__(self, *args, **kws):
cls.__init__(self, *args, **kws)
def diverge(self, func):
func(self)
_dvattr_name = self._divergence_point # to avoid confusion
if hasattr(self, _dvattr_name):
_dvgattr = getattr(self, _dvattr_name)
if isinstance(_dvgattr, list):
for _dvp in _dvgattr:
_dvp.diverge(func)
else:
if isinstance(_dvgattr, cls):
_dvgattr.diverge(func)
return DivergentClass
return class_rebuilder
"""
This decorator is used as follows:
@divergent("children")
class Tree:
def __init__(self, a, b, children):
self.a = a
self.b = b
self.children = children
@proprety
def children(self):
return self._children
@children.setter
def children(self, children):
self._children = children # this is going to be either a single element of type Tree, or a list of Tree elements.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment