Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

doctest

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:

  • Loop on globals and check if the object is a callable. The problem is that globals is a dict and thus not ordered.
  • Using the doctests directly is not convenient because the "stop at first error" won't work for me as I have several functions to test.
like image 594
Gra Avatar asked Dec 25 '22 14:12

Gra


2 Answers

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.

like image 141
Martijn Pieters Avatar answered Apr 28 '23 13:04

Martijn Pieters


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__)
like image 35
Gra Avatar answered Apr 28 '23 14:04

Gra