I have a metaclass that just append a prefix to the classes on my modules. So far so good, the problem is that I want to remove the definition of the class that is calling the metaclass. For example if class A
is prefixed to PrefixA
I will end with both classes on my globals but I just want PrefixA
on it. For now to achieve my goal I'm doing something like this:
class PrefixChanger(type):
prefix = 'Prefix'
to_delete = []
def __new__(cls, clsname, bases, attrs):
new_cls = type.__new__(cls,cls.prefix+clsname,bases,attrs)
globals()[cls.prefix+clsname] = new_cls
cls.to_delete.append(clsname)
return new_cls
@classmethod
def do_clean(cls):
gl = globals()
for name in cls.to_delete:
del gl[name]
class A(object):
__metaclass__ = PrefixChanger
class B(PrefixA):
pass
PrefixChanger.do_clean()
The problem with this approach is that I have to put the last line PrefixChanger.do_clean()
at the end of every module that uses my metaclass.
So, there is any way to do this the right way? I mean that the metaclass (or some kind of black magic) deletes the unwanted classes from the globals as soon as possible (maybe right after theirs definitions).
I'm interested on complete the task this way but some suggestions for doing it using another approach are welcome too.
Also my solution breaks on this case:
class B(object):
class C(object):
__metaclass__ = PrefixChanger
Extra credits to the one that solves it!