I'm experiencing some really weird problems in Python when trying to inherit from a class with a metaclass. I have this:
class NotifierMetaclass(type):
def __new__(cls, name, bases, dct):
attrs = ((name, value) for name, value in dct.items()
if not name.startswith('__'))
def wrap_method(meth):
return instance_wrapper()(meth) # instance_wrapper is a decorator of my own
def is_callable(value):
return hasattr(value, '__call__')
decorated_meth = dict(
(name, value) if not is_callable(value)
else (name, wrap_method(value))
for name, value in attrs
)
return super(NotifierMetaclass, cls).__new__(
cls, name, bases, decorated_meth
)
class Notifier(object):
def __init__(self, instance):
self._i = instance
__metaclass__ = NotifierMetaclass
And then, in notifiers.py:
from helpers import Notifier
class CommentNotifier(Notifier):
def __notification__(self, notification):
return '%s has commented on your board' % self.sender
def __notify__(self):
receivers = self.retrieve_users()
notif_type = self.__notificationtype__()
for user in receivers:
Notification.objects.create(
object_id=self.id,
receiver=user,
sender_id=self.sender_id,
type=notif_type
)
However, when I try to import CommentNotifier it returns Notifier. In the shell:
$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from logic.notifiers import CommentNotifier
>>> CommentNotifier
<class 'helpers.CommentNotifier'>
In fact, this is (at least that's what I think) actually the same problem I got a week ago with some Django models. At first I thought it was related to the way Django works, but now I suspect it's more like a Python "problem" with metaclasses and inheritance.
Is this a known issue or am I simply doing things wrong? Hope you can help me.
EDIT: I forgot to mention that I attribute this "error" to metaclasses because if I don't give a metaclass to Notifier it works as expected.