functions in modules are getting executed first and print statements are not getting executed even after placing them first(Before the function call)

I am new to python and trying out my own pet project. So, my project directories look like this:
enter image description here

Now in my file I have imported models module
from models.eq_melting import * from models.frac_melting import *. After that I put some print statements :
enter image description here

Now the problem is whatever function that is residing in files of module models, is getting executed first rather than the print statements.
enter image description here

Please help me to understand why this is happening.

>Solution :

When you import a module you are in fact executing it, so every statement in the module will get run. If it is just function defs then you will just add those functions to the namespace, but not actually run the code they contain. However if it contains print or other statements then they will get executed.

To summarise when you import a module you execute everything in that module.

This is also why you see very often code that looks like
if __name__ == "__main__" at the bottom of many modules. If the module gets imported the if condition won’t be satisfied, but if the module is executed directly as a script then the if condition will be satisfied and the code will run.

As a side note you should do your best to avoid from module import * – it will make debugging ten times harder as it makes it impossible for the computer (and the human) to know where items in its name space came from.

Leave a Reply