473,400 Members | 2,163 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,400 software developers and data experts.

Dynamically add Class to Modules

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.

Dec 8 '05 #1
5 3704
ca********@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

Dec 8 '05 #2
ca********@gmail.com writes:
So: Does anyone know how dynamically generate a class, and add it to a
"module" that is already in memory?


How about adding a step:

generate your class to a file
import the file as a module.
bind a name in "module" to the class in the imported module.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 8 '05 #3
Hi Michael... It didn't seem to take. Here is some of the actual code:

[[[[[[[[[[ from the runner ]]]]]]]]]]]]]
print "+++++++++++++++++++++++++++++++++++++++"
print "::Dir before exec:",dir(testModule)
import CodeGenBase
if hasattr( testModule,"TheTestCode" ):
print testModule.TheTestCode
%(testModule.TheTestName,

testModule.TheTestName )
exec testModule.TheTestCode
%(testModule.TheTestName,

testModule.TheTestName )

else:
print "PASSING"
print "::Dir after exec:",dir( testModule )
print "+++++++++++++++++++++++++++++++++++++++"

[[[[[[[[[[[[[[[[[[[ from the test file ]]]]]]]]]]]]]]]]]]]]
TheTestName = "FOO_TEST_NAME"
TheTestCode = \
"""class %sTestCase( CodeGenBase.CodeGenBase ):
def __init__( self,methodName ):
CodeGenBase.CodeGenBase.__init__( self,methodName )

def test%s(self):
self.SetupAndRunConfigTxtTests()

"""
......It doesn't look like the new class is sticking. Below is some
output:
+++++++++++++++++++++++++++++++++++++++
::Dir before exec: ['BuildRunBase', 'CodeGenBase', 'ConfigHelper',
'TheTestCode'
, 'TheTestName', '__builtins__', '__doc__', '__file__', '__name__',
'isSupported
', 'os', 'sys']
class FOO_TEST_NAMETestCase( CodeGenBase.CodeGenBase ):
def __init__( self,methodName ):
CodeGenBase.CodeGenBase.__init__( self,methodName )

def testFOO_TEST_NAME(self):
self.SetupAndRunConfigTxtTests()
::Dir after exec: ['BuildRunBase', 'CodeGenBase', 'ConfigHelper',
'TheTestCode',
'TheTestName', '__builtins__', '__doc__', '__file__', '__name__',
'isSupported'
, 'os', 'sys']
+++++++++++++++++++++++++++++++++++++++

Hopefully I just missed something obvious, which happens all too often.
Any ideas?

Thanks again for the help!

Dec 9 '05 #4
Oh! I see what I missed. I didn't supply the namespace into which the
new class was going to be added (correct that statement, please, if it
is incorrect).

So by using this slight modification, thinks seemed to work:
exec testModule.TheTestCode %(testModule.TheTestName,

testModule.TheTestName ) in testModule.__dict__

....and boom it appeared in the 2nd dir.

Did i do good?

Dec 9 '05 #5
ca********@gmail.com wrote:
....
exec testModule.TheTestCode %(testModule.TheTestName, testModule.TheTestName )


....

Try changing that to exec ~ in testModule.__dict__

otherwise, your class statement gets executed in the current scope

Michael

Dec 9 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: user | last post by:
Hi, I'm writing a DBI for my company's database. I will have one class for each of the tables in the database. I would then like each class, once instantiated, to be able to read the field...
8
by: Philippe C. Martin | last post by:
Hi, I'm getting pretty desperate here: The code below crashes on the last line (but works from a shell). The class 'BC' exists and the loop on self.__BC_EXEC_LIST passes fine. It's got to...
5
by: Christoph Haas | last post by:
Dear coders... I'm working on an application that is supposed to support "plugins". The idea is to use the plugins as packages like this: Plugins/ __init__.py Plugin1.py Plugin2.py...
11
by: Larry | last post by:
is there a way to add a class property an run-time? If so, how? any code samples? *** Sent via Developersdex http://www.developersdex.com ***
15
by: Amit D.Shinde | last post by:
I am adding a new picturebox control at runtime on the form How can i create click event handler for this control Amit Shinde
4
by: Stu | last post by:
Hi, I'm looking at making a piece of software which will have a central executable file, and a list of DLLs (kind of like Office "add-ins") that will provide different functionalities - the idea...
14
by: Jamey Shuemaker | last post by:
Greetings all, I've been reading for the last couple hours posts on this site and various MS sites about reference libraries and class modules. System: Windows 2K running an A2K db with...
32
by: Matias Jansson | last post by:
I come from a background of Java and C# where it is common practise to have one class per file in the file/project structure. As I have understood it, it is more common practice to have many...
36
by: Martin Larsen | last post by:
Hi, When a PHP program links to a library using include or require (or their _once variations), is the library then linked dynamically or statically? While it might seem irrelevant from a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.