Importing a .py file opens it on startup of another file

Question:

I am importing a settings.py file into browser.py, like so:

import settings

But when I run the browser.py file then it opens settings.py before it runs browser.py, and I don’t want settings.py to run. Is there a way to stop settings.py from running, while still importing settings into browser.py?

Asked By: Formula1Fan43

||

Answers:

Any python code outside functions and classes will be automaticly ran when you import the settings file.

You can try put the code that you don’t to be executed inside a function in the settings file and then calling those functions in browser.py as you need them.

Answered By: Luís Ferreirinha

You want to check in your settings.py file to see if that file was run directly by the user, or if it was included by some other module. The way to do that is with the __name__ variable. That variable is always defined by Python. If you are in the file that was run directly, it’s value will be __main__. So, in settings.py, do something like the following:

<code you want to always have take effect, usually functions, class definitions, global variables, etc.>

if __name__ == '__main__':
    <code you only want to run if this file was run directly>

It is common to use this mechanism to provide some test code for a module. Here’s simple concrete example of that:

def some_function(a, b, c):
    print(a, b, c)

def test():
    some_function(123, 234, 456)

if __name__ == '__main__':
    test()

So this just defines some_function and test, but doesn’t run them if it is included by some other Python file. If it is run directly, then test() is run to test the some_function() function.

Answered By: CryptoFool
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.