2

I have written a python file a.py like this:

x = 1
def hello():
   print x

hello()

When I do import a, it is printing the value of x

Till now my understanding is import will include the variables and function definitions but why it is executing the method hello()?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2753523
  • 473
  • 2
  • 8
  • 23

4 Answers4

6

Python imports are not trivial, but in short, when a module gets imported, it is executed top to bottom. Since there is a call to hello, it will call the function and print hello.

For a deeper dive into imports, see:

To be able to use a file both standalone and as a module, you can check for __name__, which is set to __main__, when the program runs standalone:

if __name__ == '__main__':
    hello()

See also: What does if __name__ == "__main__": do?

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
4

In Python, there is no clear separation between declaring and executing. In fact, there are only execution statements. For example, def hello():... is just a way to assign a function value to the module variable hello. All the statements in the module are executed in their order once the module is imported.

That's why they often use guards like:

if __name__=='__main__':
   # call hello() only when the module is run as "python module.py"
   hello()
bereal
  • 32,519
  • 6
  • 58
  • 104
1

You have called hello() function at the bottom, so when you do "import a" it will execute that function!

no1
  • 717
  • 2
  • 8
  • 21
0

you need to remove the hello() at the end, that is what is executing the function. You only want the declarations in your file a.py

koldrakan
  • 169
  • 1
  • 5