m3hran
m3hran

Reputation: 131

Issue with import in python

So, I'm quite new to python, and I tried to import a function that I had written in one of my files into another file that I was working on.

Here is the code in the file that I'm trying to import the function from:

def print_me(x):
    return 2 * x

print(print_me(5))

Here is the code in my other file:

from question2 import print_me

print(print_me(5))

Now when I run my second file, the answer (10) gets printed twice. I want to know the reason why my print function in my first file (from which I imported my function) also gets executed.

Upvotes: 0

Views: 39

Answers (2)

Saeed
Saeed

Reputation: 4123

When import a module, in fact you're importing the whole codes from that file, including print statements and others.

In order to reach this, you should either remove print statement in the first file where you define print_me function, or add this code to your file:

if __name__ == "__main__":
    # your code goes here

Have Fun :)

Upvotes: 1

Alex Mandelias
Alex Mandelias

Reputation: 517

When you import a file, every statement in this file is executed. Therefore both the def statement and the print function call are executed, printing "10" once. Then the code from your other file is executed, printing "10" a second time.

The proper way to deal with this issue is to put all the code that shouldn't be executed on import inside this block:

if __name__ == "__main__":
    # code that should not be executed on import

This ensures that the code from the first file is only executed when run.

Upvotes: 0

Related Questions