I’m trying to take a python class (in IronPython), apply it to some data and display it in a grid. The results of the functions become columns on the grid, and I would like the order of the functions to be the order of the columns. Is there a way to determine the order of python functions of a class in the order they were declared in the source code? I’ll take answers that use either IronPython or regular python.
So for instance, if I have a class:
class foo:
def c(self):
return 3
def a(self):
return 2
def b(self):
return 1
I would like to (without parsing the source code myself) get back a list of [c, a, b]. Any ideas?
As a caveat, IronPython used to keep the references of functions in the order they declared them. In .NET 4, they changed this behavior to match python (which always lists them in alphabetical order).
In Python 2.X (IronPython is currently on Python 2) the answer is unfortunately no. Python builds a dictionary of the class members before creating the class object. Once the class is created there is no ‘record’ of the order.
In Python 3 metaclasses (which are used to create classes) are improved and you can use a custom object instead of a standard dictionary to collect class members as the class is built. This allows you to know the order.
However, for IronPython there is a hack that might work. Python dictionaries are inherently unordered – i.e. iterating over the members of a dictionary returns them in an arbitrary (but stable) order. In IronPython it used to be the case that, as an accident of implementation, iteration would return members in the order they were inserted. (Note that this may no longer be the case.)
You could try:
You may find that this is ordered as you hope for. Unfortunately running the code under different versions of IronPython (or other implementations of Python) is likely to return them in a different order.
Another (better but harder) approach is to use the ast module (or the IronPython parser) and walk the AST to find the entries. Not very hard, but more work.