Search code examples
pythonnamespacespytestprogram-entry-point

How to execute code in `if __name__ == "__main__"` from another python file


In my python file I have a function that takes some parameters and in the same file I have an if __name__ == "__main__" clause that runs this function with a particular set of parameters (for a user to showcase what it does). Like so,

def foo(arg1, arg2):
    pass

if __name__ == "__main__":
    arg1 = 1
    arg2 = 2
    foo(arg1, arg2)

Furthermore, I also have another file with tests which is used by pytest. I'd like to have one of the test run exactly what is written inside the above mentioned if clause, i.e. execute

arg1 = 1
arg2 = 2
foo(arg1, arg2)

Is this possible without copying the code to the file containing the tests?


Solution

  • Well, im no expert at that but how about redicrecting your if __name__ == "__main__": to another function and call that function from your other file?

    file1:

    def main_file1:
      arg1 = 1
      arg2 = 2
      foo(arg1, arg2)
    
    if __name__ == "__main__":
      main_file1()
    

    file2:

    from file1 import *
    
    def somefunc():
      main_file1()
    

    However, im not sure why you would want to do that anyways. Usually you only have 1 main function in your whole project to get things rolling and call other functions from there.

    And ultimately this kind of fails the purpose of a main function of a file