Dynamically add Class to Modules

Michael Spencer mahs at telcopartners.com
Thu Dec 8 17:15:52 EST 2005


callmebill at gmail.com wrote:
> I'm trying to add a class to a module at runtime.  I've seen examples
> of adding a method to a class, but I haven't been able to suit it to my
> needs.
> 
> As part of a testsuite, I have a main process X that searches
> recursively for python test files.  Those files typically have a global
> "isSupported" method, in which the file tells the test searcher "do or
> do not run me", as well as the typical TestName_TestCase class, with a
> testMyTest method.
> 
> For numerous and reasonable reasons, the TestName_TestCase class must
> be generated at runtime (i cannot use any pre-processing scripts to
> generate the testcase files).  So the external runner has to look into
> each testcase file, determine if it is supported, expand out the
> test-class code, and add that new class to that testcase in memory.
> 
> I hope this picture helps:
> 
> 
> #-------- atestcase.py --------
> def isSupported():
>     """ do a real check"""
>     return True
> 
> 
> ThisTestName = "foo"
> TestCode = \
> """
> class %s_TestCase:
>     def __init__( self ):
>         """ do some stuff"""
> 
>     def test_%s( self ):
> 	""" run the test """
> """
> #------------------------------------
> 
> 
> #------- The external runner --------
> 
> (essentially)
> import atestcase.py
> if atestcase.isSupported():
>     # Run this test
> 
> (here's what i'm trying to figure out)
> #--> expand atestcase.TestCode out to include "foo"
> #--> make the testcode a class
> #--> add the new foo_TestCase class to
> #    the atestcase module
> 
> #-------------------------------------
> 
> 
> So:  Does anyone know how dynamically generate a class, and add it to a
> "module" that is already in memory?
> 
> Thanks so much in advance.  My flu is heating up my brain pretty badly,
> so please ask me if I have to clarify anything above.
> 
Bill,
I think this should do it:

import atestcase as T
exec T.TestCode % T.ThisTestName in T.__dict__

If you want to substitute ThisTestName more than once, you might be better off 
using the %(name)s form, supplied with a dictionary {name: "foo"}, or you could 
look at the new string.Template class for easier string subsitution.

Michael




More information about the Python-list mailing list