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
                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').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With