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

Is there a library or python magic that allows me to perform all the functions in a file without naming them explicitly. Something very similar to what pytest does is to run all functions starting with "test _..." without ever registering them anywhere.

For example, suppose I have a.py file:

def f1(): print "f1" def f2(): print "f2" 

and suppose I have a file - my main file is main.py:

 if __name__ == '__main__': some_magic() 

so when i call:

 python main.py 

The conclusion will be:

 f1 f2 
+6
source share
2 answers

Here is the 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 attributes of module a . If the attribute is the called object, call it. This will call all the callers, so you can get it with and i.startswith('f') .

+10
source

Here's another way:

 #!/usr/local/bin/python3 import inspect import sys def f1(): print("f1") def f2(): print("f2") def some_magic(mod): all_functions = inspect.getmembers(mod, inspect.isfunction) for key, value in all_functions: if str(inspect.signature(value)) == "()": value() if __name__ == '__main__': some_magic(sys.modules[__name__]) 

It will call functions that do not have any parameters using the .signature (function) validation function.

0
source

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


All Articles