Why any code of Imported module is executed when you not calling any of its function

Inside m2.py, you are importing m1.py. However, no function of m1.py is called inside m2.py. Then why the code of m1 is being invoked.

Hello @janofass,

Its due to the fact that when you import a file/module in python. It is first compiled and is then loaded in the memory with the namespace you specified. Look for a .pyc in the directory, that is the compiled version of your imported python file.
Hence, when you import m1 in m2, the content in the m1 is compiled or you can say executed. This is the reason we have if __name__ == "__main__": blocks.
Put the executable codes that you need in this block and keep all the classes/functions outside. So when imported, __name__ var is not __main__ and anything inside the block is not executed.

To have a better understanding of this, try:

in module1.py

print("In module 1:", __name__)

in module2.py

import module1
print("In module 1:", __name__)

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.