Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - inspect.getmembers in source code order

Tags:

python

inspect

I am trying to get a list of functions from a module using inspect.getmembers in the order of source code.

Below is the code

def get_functions_from_module(app_module):
    list_of_functions = dict(inspect.getmembers(app_module, 
    inspect.isfunction))

    return list_of_functions.values

The current code will not return the list of function objects in order of the source code and I'm wondering if it would be possible to order it.

Thank you!

like image 812
Young Avatar asked Nov 02 '17 18:11

Young


1 Answers

I think I came up with a solution.

def get_line_number_of_function(func):
    return func.__code__.co_firstlineno

def get_functions_from_module(app_module):
        list_of_functions = dict(inspect.getmembers(app_module, 
        inspect.isfunction))

    return sorted(list_of_functions.values(), key=lambda x:
           get_line_number_of_function(x))
like image 168
Young Avatar answered Oct 22 '22 09:10

Young