[Python-ideas] Modify inspect.getmembers() to return object members in source code order

Cem Karan cfkaran2 at gmail.com
Mon Mar 16 01:02:31 CET 2015


I'd like to suggest that inspect.getmembers() be modified to return elements in the order they are defined in the source code rather than in alphabetical order.  For people that want the output in sorted order, the call would become 'sorted(inspect.getmembers())', which is relatively easy to do.  For me, and anyone else that is generating code from source code, the advantage is that the generated code is 'in the right order'.  As an example, consider generating unit tests for code that really should have had unit tests as the code was written, but didn't[1].  If inspect.getmembers() returned the elements in the same order as they appear in the source code, then we can generate code similar to the following[2]:

"""
members = inspect.getmembers(SomeoneNeedsToCleanThisUp)
names = [x[0] for x in members]

def test_gen(name):
    return ("    def test_{0!s}(self):\n".format(name) +
            "        raise NotImplementedError('He Who Shall Not Be Named, But Is On My Special List had better fill this in NOW!')\n" +
            "    # End of test_{0!s}()\n".format(name))

tests = "\n".join([test_gen(x) for x in names])
# Writing out names to the right location, etc.
"""

Thoughts?

Thanks,
Cem Karan

[1] This may possibly be the reason why I want to propose this change...
[2] Banged out in Mail.app very quickly, may have bugs, and definitely is not production code.


More information about the Python-ideas mailing list