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:
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.
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With