The main
is just a Python variable that points to the function object. If you assign the main
a different value, you loose the reference to the original function. If you define the main
after the import, then your own main
will be used.
Update: If both file1.py
and file2.py
contain the definition of the main()
function and if both call it in the file -- say as the last line in its own file, and if the file1.py
does import file2
--but does not from file2 import *
after the main()
definition in the file1.py
--then both main()
functions will be called. The file2.main()
is called during the import file2
(the first import in the application only), and the file1.main()
is going to be called when the main()
call in file1.py
is found.
Whenever xxx.py
is launched as a script, it is processed in the order of the source text. Processing of a definition means compilation of the definition, when a command is found during the first read, it is executed (actually after compilation to xxx.pyc
first).
The only way to avoid execution of a code in your file is to jump over the code fragment using if
with suitable condition. This is why the pattern
if __name__ == '__main__':
main()
is used in the sources. (Which actually is the execution of the code -- only the branch of the if
is skipped.) Read it... If the file is launched as a script, then the __name__
variable takes the string value '__main__'
, the condition holds and the main()
from this file is called.
If the same pattern is used in the file2.py
, and the file is used as a module (that is import file2
), then the __name__
variable contains the name of the imported module (here file2
), and the condition does not hold. Because of that, the main()
from inside file2.py
is not called.
The pattern is often used even in the files that are expected to be used as modules only. The code is usually used for testing the basic functionality of the module. Think about the situation when the author of the module makes some changes. Then he/she launches it as a script (which is not usually doney), and the body starts testing of the module and reports the result -- say using unittest
module or whatever kind of testing. So, the file2.main()
would be a good place to activate unit testing, for example.
Try to add the following to the end of your file1.py
:
print(__name__)
print(file2.__name__)