xel
xel

Reputation: 125

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?

Upvotes: 1

Views: 4062

Answers (2)

DJSchaffner
DJSchaffner

Reputation: 582

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

Upvotes: 2

Reedinationer
Reedinationer

Reputation: 5774

If you have the files

file1.py

def foo(arg1, arg2):
    pass

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

and file2.py is in the same directory you can:

file2.py

from file1 import foo
arg1 = 1
arg2 = 2
foo(arg1, arg2)

You will need to redefine arg1 and arg2 like you have, but then its just a matter of importing the function you'd like. This will give you the function, but none of the global variables of file1.py because these are protected by the if __name__ == "__main__" statement

UPDATE

If you don't want to have to reassign within file2.py you can do something like this:

file1.py

def foo(arg1, arg2):
    pass

def new_function(): #make a new function that you can import
    arg1 = 1
    arg2 = 2
    foo(arg1, arg2)

if __name__ == "__main__":
    new_function()

file2.py

from file1 import new_function
new_function()

This is not the worst because you are still containing arg1 and arg2 as local variables so there is not a huge namespace concern, but now you can import them because they are not protected within the if name == main section of your code.

Upvotes: 1

Related Questions