سؤال

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.
هل كانت مفيدة؟

المحلول 2

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__)

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top