Reflection in Python?

rwentwor at rwentwor at
Wed Jun 30 15:14:45 EDT 1999

Assuming you're working with Python class instance objects,
something like the following might work:

     # define class
     class SillyMathTest:
          def testAdd(self, x, y):
               return x+y

     # create class instance object
     MathTest = SillyMathTest()

     # get reference to bound method MathTest.testAdd
     test = getattr(MathTest, "testAdd")

     # effectively do MathTest.testAdd(3,5)

As to getting naming info: well, you already have the
name of the method as a string, you can get the name of
the class as MathTest.__class__.__name__, but there
is no way to extract the string "MathTest" from the
MathTest object because "MathTest" is the name of
a variable referencing the object, not something that
is really part of the object.  (You couldn't do this in
Java either, so I'm not sure what you had in mind.)

Bob Wentworth

--original message--
I've just started programming in Python, and I
could really use some help figuring out something.
 I'd like to implement Kent Beck's unit tester in
Python (someone posted a very nice alternative a
few weeks ago, but Junit's approach works better
for my project's needs).  How do I do the
equivalent of what Java calls reflection? I wantto do the

     test = MathTest("testAdd")

where will run the "testAdd" method on
the MathTest object?  I also want to be able to
tell the user the name of the object (MathTest)
and the method in case the method fails.  Anythoughts?

More information about the Python-list mailing list