Augustin Coman
Augustin Coman

Reputation: 25

Is it possible that importing a function from another file (python) changes the outcome of your code?

I imported a function from another python file and it makes my code run 2 times.

Code goes like this

n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)

After some lines it goes:

from Partie_C import boucle_jeu

And this importing makes this code run again:

n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)

So you understand... without it it just asks "n" prints the message and it's done (only one time)

Upvotes: 0

Views: 76

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45826

The only reasonable way what you're describing could happen is if Partie_C is importing the file containing n = ..., causing a circular import.

A circular import will cause the code to run twice because importing will cause the imported file to be interpreted. If you import Partie_C, it will run. If Partie_C then imports this code, this code will run as a result of the import.

# Code runs here obviously
n = int(input("\nCombien des disques? \nNombres des disques: "))  
display = init(n)
print("\nYour playground looks like this: \n", display)

 # Indirectly imports this file, causing the whole file to be interpreted again, running the above code again
from Partie_C import boucle_jeu

To fix this, either put the code in a function instead of being top level, or use an import guard (if __name__ == "__main__"). Or better yet, don't have circular imports. Circular imports are generally considered to be a code smell. Rearrange your code so you don't have two files importing each other.

Upvotes: 1

Related Questions