1

For example a class is defined as follows

>>> class sample(object):
...     def step_1(self):
...         pass
...     def step_2(self):
...         pass
...     def step_10(self):
...         pass
...     def step_5(self):
...         pass
... 
>>> d = sample()
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'step_1', 'step_10', 'step_2', 'step_5']

dir(d) is returning sorted list of instance methods. My requirement is get the names defined in the class in the same order as they defined i.e, (step_1,step_2,step_10,step_5)

**Answer :** Added additional method 'getTestSteps' to the class to acheive the same:

>>> import types
>>> 
>>> class sample(object):
...     def step_1(self):
...         pass
...     def step_2(self):
...         pass
...     def step_10(self):
...         pass
...     def step_5(self):
...         pass        
...     def getTestSteps(self):
...         def first_lineno(name):
...            method = getattr(self.__class__, name)
...            return method.im_func.__code__.co_firstlineno
...         temp = self.__class__
...         skipMethodList = ['setUp','tearDown']
...         testFnNames = [x for x,y in temp.__dict__.items() if type(y) == types.FunctionType and x not in skipMethodList]
...         testFnNames.sort(key=first_lineno)
...         return testFnNames
... 
>>> d = sample()
>>> d.getTestSteps()
['step_1', 'step_2', 'step_10', 'step_5', 'getTestSteps']
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'getTestSteps', 'step_1', 'step_10', 'step_2', 'step_5']
Surya
  • 65
  • 9
  • Why do you want to do that? There should only be one function in there, anyway, with a parameter for the step size. – TigerhawkT3 Jan 05 '16 at 10:48
  • Thanks @vaultah, I didn't find answer for the same, so I have posted the question. I have added the following method under the class to get the same def getTestSteps(self): def first_lineno(name): method = getattr(self.__class__, name) return method.im_func.__code__.co_firstlineno temp = self.__class__ skipMethodList = ['setUp','tearDown'] testFnNames = [x for x,y in temp.__dict__.items() if type(y) == types.FunctionType and x not in skipMethodList] testFnNames.sort(key=first_lineno) return testFnNames – Surya Jan 06 '16 at 07:20
  • @Surya: looks like your solution should work. I think you'd generalize it and post it as an answer to the linked question. – vaultah Jan 06 '16 at 09:07

0 Answers0