| 1 |
def jit_mixin(obj, mixin): |
| 2 |
"""Apply mixin to object and return the object""" |
| 3 |
if not isinstance(obj, mixin): |
| 4 |
obj.__class__ = jit_mixin_type(obj.__class__, mixin) |
| 5 |
return obj |
| 6 |
|
| 7 |
|
| 8 |
def jit_mixin_type(base, *mixins): |
| 9 |
assert not issubclass(base, mixins), (base, mixins) |
| 10 |
mixed = _mixin_cache.get((base, mixins)) |
| 11 |
if mixed is None: |
| 12 |
prefix = "".join(m._jit_mixin_prefix for m in mixins) |
| 13 |
name = f"{prefix}{base.__name__}" |
| 14 |
mixed = _mixin_cache[(base, mixins)] = type(name, (*mixins, base), { |
| 15 |
"_jit_mixin_base": getattr(base, "_jit_mixin_base", base), |
| 16 |
"_jit_mixins": mixins + getattr(base, "_jit_mixins", ()), |
| 17 |
}) |
| 18 |
return mixed |
| 19 |
|
| 20 |
|
| 21 |
_mixin_cache = {} |
| 22 |
|
| 23 |
|
| 24 |
class JITMixin: |
| 25 |
|
| 26 |
def __reduce__(self): |
| 27 |
# make JITMixin classes pickleable |
| 28 |
return (jit_mixin_type, (self._jit_mixin_base, *self._jit_mixins)) |