user2753523
user2753523

Reputation: 483

What exactly import will do in python

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()?

Upvotes: 2

Views: 95

Answers (4)

miku
miku

Reputation: 188024

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?

Upvotes: 6

bereal
bereal

Reputation: 34282

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()

Upvotes: 4

koldrakan
koldrakan

Reputation: 169

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

Upvotes: 0

no1
no1

Reputation: 727

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

Upvotes: 1

Related Questions