1

I am learning python3 and I am learning import statement.

I have two python files.

In fiboo.py I have following codes:

x=10

y=x+15

print("hello from fiboo")

def hello():
    print("i am ashwin")

In main.py I have following codes:

from fiboo import y

print("hello from main")
print(y)

I want to access only the y variable.So,I did from fiboo import y. But I see that 'hello from fiboo' also being printed.Will all the codes get runned even if I import specific variables from modules? While running the above code I see output as:

[Running] python -u "d:\python practise\main.py"
hello from fiboo
hello from main
25

Again I changed the code as:

import fiboo

print("hello from main")
print(fiboo.y)

Here also I see output as:

Running] python -u "d:\python practise\main.py"
hello from fiboo
hello from main
25

Does python compiles the whole code of modules even if we use from module import y kind of statement? Doesn't it only import y variable from fiboo.py file while I use from module import y? Where is the optimization then if the whole code gets compiled if we only want variable y from another module? Or it is the rules that whole modules code gets compiled and printed no matter if we use from fiboo import y or import fiboo ?

  • https://stackoverflow.com/questions/419163/what-does-if-name-main-do?page=2&tab=Votes#:~:text=if%20__name__%20%3D%20%22__main,will%20not%20run%20the%20function. – DeepSpace Oct 25 '21 at 14:13
  • Does [this](https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) answer your question? – Cory Kramer Oct 25 '21 at 14:14
  • It's not about compilation, per se. It actually runs the code in the imported module. – jarmod Oct 25 '21 at 14:18
  • @jarmod can you help me explain more about this – Dikshit Karki Oct 25 '21 at 15:13
  • Regardless of how you import a module, the code in that module is run (first time, after that it's cached in sys.modules). You ran main, it imported something (doesn't matter what) from fiboo, so fiboo was run. You can learn more about [import](https://realpython.com/lessons/import-statement/). – jarmod Oct 25 '21 at 15:38

0 Answers0