I need to call if __name__ == '__main__'
, that calls several classes in one module, Module 1
, in a function, function1
, that's in a class in a second module, Module 2
.
I can't use def main()
- solution in Module 1
instead of if __name__ == '__main__'
, since the module has several classes and functions connected to Class_1
in Module 1
that only works with print('I am:', __name__)
and if __name__ == '__main__':
.
So my question is how I can call main: if __name__ == '__main__'
from Class_1()
in function1
in Class_2()
in Module 2
?
Module 1
print('I am:', __name__)
class Class_1():
....code...
# calling everything in the module that
if __name__ == '__main__':
Module 2
# if __name__ == '__main__' from Module 1 should be called in function 1
class Class_2():
.... code..
def function1:
--- calling main if __name__ == '__main__' from Module 1
The if __name__ == '__main__'
is mainly used to make a single python script executable. For instance, you define a function that does something, you use it by importing it and running it, but you also want that function to be executed when you run your python script with python module1.py
.
For the question you asked, the best I could come up with is that you wanted a function defined in "module1.py" to run when you invoke "module2.py". That would be something like this:
### module1.py:
def main():
# does something
...
if __name__ == '__main__':
main()
### module2.py:
from module1 import main as main_from_module_one
if __name__ == '__main__':
main_from_module_one() # calling function main defined in module1
The whole point of the if __name__...
is that it's for things that are only needed when the module is executed as a script, ie exactly if it's not being imported from another class. So no, you don't need to do this.
Your explanation of why you can't put things into a function make no sense; that is exactly what you should do.