Making helper methods more concise
Arnaud Delobelle
arnodel at gmail.com
Mon Apr 16 08:29:10 EDT 2012
On 16 April 2012 13:01, Alan Ristow <alan.ristow at gmail.com> wrote:
> 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.
You can do this (untested), but no doubt it won't be to everybody's taste:
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.
for style in 'paragraph', 'header', 'title':
exec """def append_%s(self, text):
self.append_text(text, "%s")""" % (style, style.capitalize())
del style
--
Arnaud
More information about the Python-list
mailing list