String handling and the percent operator

Tom Plunket gamedev at fancy.org
Thu Jul 13 18:49:47 EDT 2006


I have some code to autogenerate some boilerplate code so that I don't
need to do the tedious setup stuff when I want to create a new module.

So, my script prompts the user for the module name, then opens two
files and those files each get the contents of one of these functions:

def GetPyContents(module):
	boilerplate = \
"""
class %s:
	pass
	
if __name__ == '__main__':
	import unittest
	unittest.main('%s_t')
"""
	
	return boilerplate % ((module,) * 2)
	
def GetTestContents(module):
	boilerplate = \
"""from %s import *
import unittest

class Test%s(unittest.TestCase):
	def testConstruction(self):
		self.failUnless(%s())
		
	def testWriteMoreTests(self):
		self.fail('This test should fail.')
		
if __name__ == '__main__':
	unittest.main()
"""

	return boilerplate % ((module,) * 3)

My question is, I don't like hardcoding the number of times that the
module name should be repeated in the two return functions.  Is there
an straight forward (inline-appropriate) way to count the number of
'%s'es in the 'boilerplate' strings?  ...or maybe a different and more
Pythonic way to do this?  (Maybe I could somehow use generators?)

thx.
-tom!



More information about the Python-list mailing list