Making helper methods more concise

Alan Ristow alan.ristow at gmail.com
Mon Apr 16 08:01:58 EDT 2012


Hi all,

I have defined a class that includes a number of helper methods that
are useful to me, but pretty redundant. Something like so, where I
maintain a list of tuples:

class A(object):
    def __init__(self):
        self.listing = []

    # This method does the work.
    def append_text(self, text, style):
        self.listing.append((text, style))

    # The rest of the methods are just helpers.
    def append_paragraph(self, text):
        self.append_text(text, 'Paragraph')

    def append_header(self, text):
        self.append_text(text, 'Header')

    def append_title(self, text):
        self.append_title(text, 'Title')

obj = A()
obj.append_title('On Learning Something New About Python')
obj.append_header('A Question Is Posed')
obj.append_paragraph('Where is lorem ipsum when you need it?')


To me, this code is simple, clear, and easy to maintain, but
incredibly redundant. That's fine, I have no problem with that, but it
got me thinking: Is there a way to make the code more concise?

I know that concise is not necessarily better, but I am asking
primarily to educate myself rather than to improve this particular
piece of code -- the code only inspired the question. I'm trying to
wrap my head around decorators (aside from the simplest ones) and
metaclasses at the moment, so feel free to throw those sorts of
solutions into the mix if something like that would be appropriate.

Thanks,

Alan



More information about the Python-list mailing list