pythonsubclassclass-variables

Enforcing Class Variables in a Subclass


I'm working on extending the Python webapp2 web framework for App Engine to bring in some missing features (in order to make creating apps a little quicker and easier).

One of the requirements here is that each subclass needs to have some specific static class variables. Is the best way to achieve this to simply throw an exception if they are missing when I go to utilise them or is there a better way?

Example (not real code):

Subclass:

class Bar(Foo):
  page_name = 'New Page'

page_name needs to be present in order to be processed here:

page_names = process_pages(list_of_pages)

def process_pages(list_of_pages)
  page_names = []

  for page in list_of_pages:
    page_names.append(page.page_name)

  return page_names

Solution

  • Abstract Base Classes allow to declare a property abstract, which will force all implementing classes to have the property. I am only providing this example for completeness, many pythonistas think your proposed solution is more pythonic.

    import abc
    
    class Base(object):
        __metaclass__ = abc.ABCMeta
    
        @abc.abstractproperty
        def value(self):
            return 'Should never get here'
    
    
    class Implementation1(Base):
    
        @property
        def value(self):
            return 'concrete property'
    
    
    class Implementation2(Base):
        pass # doesn't have the required property
    

    Trying to instantiate the first implementing class:

    print Implementation1()
    Out[6]: <__main__.Implementation1 at 0x105c41d90>
    

    Trying to instantiate the second implementing class:

    print Implementation2()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-4-bbaeae6b17a6> in <module>()
    ----> 1 Implementation2()
    
    TypeError: Can't instantiate abstract class Implementation2 with abstract methods value