'Importing a module in python without running the contents of the module every time
I'm a programming and python noob so please explain as simply as you can.
I have a program file where I obtain a neural network. This neural network changes on every run of the program due to using random training data. This file is called "main.py"
I use the obtained neural network on another program file to make some more calculations and modifications. At the start of the code, I utilize:
import main
However, every time I run the code, it also runs main.py and changes the obtained output. I would like to run main.py only once so the imported output remains consistent. How can I possibly do this?
Solution 1:[1]
At the end of your module main.py you should add the line if __name__ == "__main__", i.e.:
# main.py
def foo():
# function body
# do NOT call foo here.
if __name__ == "__main__":
# call foo here.
foo()
In this way when you import the module main the function foo will not run.
For instance, in the module 'other.py' you can import the function foo from the module main:
from main import foo
# do stuff with foo
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
