[Python-3000] mixin class decorator
tomerfiliba at gmail.com
Thu May 10 13:36:55 CEST 2007
with the new class decorators of py3k, new use cases emerge.
for example, now it is easy to have real mixin classes or even
mixin modules, a la ruby.
unlike inheritance, this mixin mechanism simply merges the
namespace of the class or module into the namespace of the
decorated class. it does not affect class hierarchies/MRO,
and provides finer granularity as to what methods are merged,
i.e., you explicit mark which methods should be merged.
"""marks a method as a mixin method"""
func.is_mixin = True
def get_unbound(obj, name):
if name in obj.__dict__:
for b in obj.mro():
if name in b.__dict__:
def mixin(obj, override = False):
"""a class decorator that merges the attributes of 'obj' into the class"""
for name in dir(obj):
attr = get_unbound(obj, name)
if getattr(attr, "is_mixin", False):
if override or not hasattr(cls, name):
setattr(cls, name, attr)
for k in self.keys():
def has_key(self, key):
value = self[key]
for key in self.keys():
md = MyDict()
for k in md:
does it seem useful? should it be included in some stdlib?
or at least mentioned as a use case for class decorators in PEP 3129?
(not intended for 3.0a1)
More information about the Python-3000