Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of the names of all functions in a Python module in the order they appear in the file?

The globals function returns a dictionary that contains the functions in a module, and the dir function returns a list that contains the names of the functions in a module, but they are in alphabetical order or are in a dictionary.

Is there a way to get the names of all the functions in a module in the order they appear in a file?

like image 306
davidscolgan Avatar asked Sep 01 '25 20:09

davidscolgan


1 Answers

When I had a need like this, I used a decorator.

def remember_order(func, counter=[0]):
    func._order = counter[0]
    counter[0] += 1
    return func

@remember_order
def foo():
    print "foo"

@remember_order
def bar():
    print "bar"

@remember_order
def baz():
    print "baz"

Yes, you have to decorate each function individually. Explicit is better than implicit, as they say, and because you are doing something unnatural it's good to call it out as plainly as possible.

Now you want to get all the decorated functions in the order they were defined?

import sys
module = sys.modules[__name__]   # get reference to current module
# you could also use a reference to some other module where the functions are

# get the functions in the order defined
funcs = sorted((func for func in
              (getattr(module, name) for name in dir(module))
              if callable(func) and hasattr(func, "_order")),
              key = lambda func: func._order)

# call them in that order
for func in funcs:
    func()

But it'd be easier to just give them names in alphabetical order...

like image 88
kindall Avatar answered Sep 06 '25 12:09

kindall