0

What is the best practice for automatically executing all of the functions in the script? Take for example this script:

def a():
    return 1

def b():
    return 100

def c():
    return 1000

How would I execute all of these functions without performing the following after running the script:

>>>a()
1
>>>b()
100
>>>c()
1000

1 Answer 1

4

You can find all function objects in your globals:

from inspect import isfunction

for obj in globals().values():
    if isfunction(obj) and obj.__module__ == __name__:
        print obj()

By testing for the __module__ attribute you filter out any imported function objects (such as the inspect.isfunction() function). This assumes that none of your functions take arguments.

Sign up to request clarification or add additional context in comments.

3 Comments

This is great. As a point of curiosity, why does the printed output appear in the following order: a(), c(), b() (i.e. 1,1000,100)?
@Aaron: because the global namespace is a dictionary, and dictionaries have no set order.
@Aaron: you could sort on names, but if you really need source code order there are tricks you can apply (the starting line number is stored with the function code object as function.func_code.co_firstlineno, you can sort on that).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.