I have a flask application, and I have split the code into multiple python files, each dedicated to a specific portion of the overall program (db, login, admin, etc). Most of the files have some sort of setup code that creates their respective module's object, which must have access to the Flask object defined in my main file. Some of the modules also need access to variables in other modules, but when importing them, they are run again, even though they were imported in main already.
The following code is an example of the problem.
If I have a main.py like this
import foo
import bar
if __name__ == "__main__":
foo.foofunc()
foo.py
import bar
@bar.barable
def foo(string):
print(string)
and bar.py
import foo
foo.foo("hello")
def barable(fun):
def r(*args, **kwargs):
print("this function is completely unbarable")
func(*args, **kwargs)
This code doesn't work because foo imports bar, which imports foo, which runs bar.barable, which hasn't been defined yet.
In this situation (assuming that calling foo.foo is necessary), is my only option to extract bar.barable out of bar and into a seperate module, or is there some other way to fix this?
I know that importing a module in python runs the file, but is there some way to put some of the code into the same sort of check as __name__ == "__main__"
but to check if it is being imported by main and not by another module?