replacing __dict__ with an OrderedDict

Peter Otten __peter__ at
Fri Jan 6 06:44:21 EST 2012

Ulrich Eckhardt wrote:

> The topic explains pretty much what I'm trying to do under Python
> 2.7[1]. The reason for this is that I want dir(SomeType) to show the
> attributes in the order of their declaration. This in turn should
> hopefully make unittest execute my tests in the order of their
> declaration[2], so that the output becomes more readable and structured,
> just as my test code (hopefully) is.
> I've been toying around with metaclasses, trying to replace __dict__
> directly, or using type() to construct the class, but either I hit
> read-only attributes or the changes seem to be ignored.

Alternatively you can write your own test loader:

$ cat
import unittest

class Test(unittest.TestCase):
    def test_gamma(self):
    def test_beta(self):
    def test_alpha(self):

class Loader(unittest.TestLoader):
    def getTestCaseNames(self, testCaseClass):
        """Return a sequence of method names found within testCaseClass
        sorted by co_firstlineno.
        def first_lineno(name):
            method = getattr(testCaseClass, name)
            return method.im_func.__code__.co_firstlineno

        function_names = super(Loader, self).getTestCaseNames(testCaseClass)
        return function_names

if __name__ == "__main__":

$ python2.7 -v
test_gamma (__main__.Test) ... ok
test_beta (__main__.Test) ... ok
test_alpha (__main__.Test) ... ok

Ran 3 tests in 0.001s


More information about the Python-list mailing list