[Tutor] How can I avoid cut'n'paste in this case?

Kent Johnson kent37 at tds.net
Sat Apr 16 20:23:03 CEST 2005


Nigel Rowe wrote:
> I have two modules, both define the same set of classes (with differing
> implementations) and a number of utility functions that use those classes.
> 
> The utility functions are identical (the differences I need are abstracted
> in the classes), so they are cut'n'pasted into both files.
> 
> A simplified concrete example (not what I'm doing, but it illustrates the
> point):
> 
> -- C.py --
> |class Comment:
> |    def __init__(self, value):
> |        self.value = value
> |
> |    def __str__(self):
> |        return "/* " + self.value + " */"
> |
> |# utility functions
> |import time
> |def stamp():
> |    return Comment(time.asctime())
> 
> 
> -- P.py --
> |class Comment:
> |    def __init__(self, value):
> |        self.value = value
> |
> |    def __str__(self):
> |        return "# " + self.value + "\n"
> |
> |# utility functions
> |import time
> |def stamp():
> |    return Comment(time.asctime())
> 
> 
> How can I refactor these modules to avoid the code duplication?

You could make stamp() a classmethod of a common base class like this:

# CommentBase.py
import time

class CommentBase(object):
     def stamp(cls):  # cls will be one of the Comment implementations
         return cls(time.asctime())

     stamp = classmethod(stamp)

# C.py
from CommentBase import CommentBase
class Comment(CommentBase):
     def __init__(self, value):
         self.value = value


# Client code
from C import Comment

c = Comment.stamp()  # This becomes CommentBase.stamp(Comment)
print type(c), c.value


Kent



More information about the Tutor mailing list