Python class structure ... prep() method?

Posted by Adam Nelson on Stack Overflow See other posts from Stack Overflow or by Adam Nelson
Published on 2010-04-02T14:44:10Z Indexed on 2010/04/02 15:13 UTC
Read the original article Hit count: 182

Filed under:

We have a metaclass, a class, and a child class for an alert system:

class AlertMeta(type):
"""
Metaclass for all alerts    
Reads attrs and organizes AlertMessageType data
"""
def __new__(cls, base, name, attrs):
    new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs)
    # do stuff to new_class
    return new_class

class BaseAlert(object):
"""
BaseAlert objects should be instantiated
in order to create new AlertItems.
Alert objects have classmethods for dequeue (to batch AlertItems)
and register (for associated a user to an AlertType and AlertMessageType)

If the __init__ function recieves 'dequeue=True' as a kwarg, then all other
arguments will be ignored and the Alert will check for messages to send
"""

__metaclass__ = AlertMeta

def __init__(self, **kwargs):
    dequeue = kwargs.pop('dequeue',None)
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)
    if dequeue:
        self.dequeue()
    else:
        # Do Normal init stuff

def dequeue(self):
    """
    Pop batched AlertItems
    """
    # Dequeue from a custom queue

class CustomAlert(BaseAlert):
    def __init__(self,**kwargs):
        # prepare custom init data
        super(BaseAlert, self).__init__(**kwargs)

We would like to be able to make child classes of BaseAlert (CustomAlert) that allow us to run dequeue and to be able to run their own __init__ code. We think there are three ways to do this:

  1. Add a prep() method that returns True in the BaseAlert and is called by __init__. Child classes could define their own prep() methods.
  2. Make dequeue() a class method - however, alot of what dequeue() does requires non-class methods - so we'd have to make those class methods as well.
  3. Create a new class for dealing with the queue. Would this class extend BaseAlert?

Is there a standard way of handling this type of situation?

© Stack Overflow or respective owner

Related posts about python