Skip to content

Instantly share code, notes, and snippets.

@unthingable unthingable/solution.py
Last active Jan 3, 2016

Embed
What would you like to do?
nuclear class splitting (https://github.com/nucleic/atom) Problem: Atom subclasses require all attributes to be Fields (subclasses of Member). In practice this means you can neither drop atomic fields into an existing class, not create new class attributes inside methods; quite annoying. Atomizer will split a class into a real Atom and a "deatom…
from atom.api import Atom, Int
# This is not OK:
class A(Atom):
x = Int()
y = 0
def f(self):
self.y = 1 # not OK
self.z = 5 # very not OK!
# This is ok!
class AtomicA(Atom):
x = Int()
class B(object):
y = 0
class C(AtomicA, B):
...
x = 5
y = 3
from atom.catom import Member
from atom.api import AtomMeta, Atom
def split_dict(d, test):
a, b = {}, {}
for k, v in d.iteritems():
if test(k, v):
a[k] = v
else:
b[k] = v
return a, b
import inspect
class AtomizerMeta(type):
def __new__(meta, class_name, bases, attrs):
module = inspect.getmodule(inspect.stack()[1][0])
if module.__name__ == meta.__module__ and class_name == 'Atomizer':
# hide the magic until the real class comes along
return super(AtomizerMeta, meta).__new__(meta, class_name, bases, attrs)
# pluck out atom fields
atom_attrs, basic_attrs = split_dict(attrs, lambda k,v: isinstance(v, Member))
# remove Atomizer, will replace with two new classes
new_bases = tuple(b for b in bases if b != Atomizer)
new_classes = {}
if not new_bases:
basic_name = class_name + '_deatomized'
basic_class = type(basic_name, new_bases, {})
new_classes[basic_name] = basic_class
new_bases += (basic_class, )
atom_name = class_name + '_atom'
atom_class = type(atom_name, (Atom,), atom_attrs)
new_classes[atom_name] = atom_class
new_bases += (atom_class, )
# inject into the containg module
for n, c in new_classes.items():
setattr(module, n, c)
setattr(c, '__module__', module.__name__) # just in case
return type(class_name, new_bases, basic_attrs)
class Atomizer(object):
'''Smart atomizer'''
__metaclass__ = AtomizerMeta
'''
Now we can do this!
from atom.api import Atom, Int
from .model import model
class A(model.Atomizer):
a = Int()
b = 0
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.