Gra
Gra

Reputation: 1594

List of Python functions, in their order of definition in the module

For a test-driven pedagogical module, I need to check doctests in a precise order. Is there a way to grab all callables in the current module, in their order of definition?

What I tried:

Upvotes: 4

Views: 129

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124258

Each function object has a code object which stores the first line number, so you can use:

import inspect

ordered = sorted(inspect.getmembers(moduleobj, inspect.isfunction), 
                 key=lambda kv: kv[1].__code__.co_firstlineno)

to get a sorted list of (name, function) pairs. For Python 2.5 and older, you'll need to use .func_code instead of .__code__.

You may need to further filter on functions that were defined in the module itself and have not been imported; func.__module__ == moduleobj.__name__ should suffice there.

Upvotes: 9

Gra
Gra

Reputation: 1594

Thanks to Martijn, I eventually found. This is a complete snippet for Python3.

import sys
import inspect

def f1():
    "f1!"
    pass
def f3():
    "f3!"
    pass
def f2():
    "f2!"
    pass

funcs = [elt[1] for elt in inspect.getmembers(sys.modules[__name__],
                                              inspect.isfunction)]
ordered_funcs = sorted(funcs, key=lambda f: f.__code__.co_firstlineno)
for f in ordered_funcs:
    print(f.__doc__)

Upvotes: 1

Related Questions