A list of Python functions in the order they are defined in the module

For the test pedagogical module, I need to check the doctrines in the exact order. Is there a way to capture all callables in the current module in the order they are defined?

What I tried:

  • Loop globally and check if the object is callable. The problem is that global variables are dict and therefore not ordered.
  • Using doctrines directly is not convenient, because "stopping on the first error" will not work for me, since I have several functions for testing.
+4
source share
2 answers

Thanks Martijn, I eventually found. This is the 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__)
0
source

, , :

import inspect

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

(name, function). Python 2.5 .func_code .__code__.

, , ; func.__module__ == moduleobj.__name__ .

+9

Source: https://habr.com/ru/post/1523926/


All Articles