Search code examples
pythonreflection

Get a list of the names of all functions in a Python module in the order they appear in the file?


The globals function returns a dictionary that contains the functions in a module, and the dir function returns a list that contains the names of the functions in a module, but they are in alphabetical order or are in a dictionary.

Is there a way to get the names of all the functions in a module in the order they appear in a file?


Solution

  • Here is my solution. Read in the source file as a string, filter out lines that begin with def, strip leading whitespace and extract the substring between the first space and first left paren.

    def extract_fns(filename):
        with open(filename) as f:
            lines = f.readlines()
            return [line.split(' ', 1)[1].split('(')[0] for line in lines
                if line.strip().startswith('def')]