Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in python to execute all functions in a file without explicitly calling them?

Tags:

python

Is there a library or a python magic that allows me to execute all functions in a file without explicitly calling them. Something very similar to what pytest is doing - running all functions that start with 'test_...' without ever registering them anywhere.

For example assume I have a file a.py:

def f1():
    print "f1"

def f2():
    print "f2"

and assume I have file - my main file - main.py:

if __name__ == '__main__':
    some_magic()

so when I call:

python main.py

The output would be:

f1
f2
like image 505
Ezra Avatar asked Feb 21 '15 07:02

Ezra


1 Answers

Here's a way:

def some_magic():
    import a
    for i in dir(a):
        item = getattr(a,i)
        if callable(item):
            item()

if __name__ == '__main__':
    some_magic()

dir(a) retrieves all the attributes of module a. If the attribute is a callable object, call it. This will call everything callable, so you may want to qualify it with and i.startswith('f').

like image 199
Mark Tolonen Avatar answered Oct 18 '22 08:10

Mark Tolonen