0

I have two Python files: one is the main file (the file that I am trying to import), the other is a Turtle file (the file that I am trying to import the main file into). I am trying to retrieve a variable from that main file to use in my Turtle file

When I try to do from main_file import variable on my Turtle file, it runs the entire main file, instead of importing that single variable.

I've tried doing the following:

1)

import main_file as this_file

2)

from main_file import *

but neither of them work.

I am using Python 3.7.3. Any help will be greatly appreciated.

sombat92
  • 109
  • 8
  • 1
    Are you familiar with the `if __name__ == "__main__":` construct? – C Haworth Jul 26 '19 at 20:05
  • 1
    Yes, that's how importing files *always* works. When you import a file, it runs the `class:` class definitions and the `def:` function definitions, and therefore defines those classes and those functions. – Charles Duffy Jul 26 '19 at 20:09

2 Answers2

2

This is normal behaviour.

  1. Importing a module actually runs its contents. This allows, among other things, several nifty things libraries do under the hood, such as configuring their components.
  2. Importing just one (or some) elements from a module actually runs the whole thing. If that weren't the case, if the element you want to import requires some global configuration from the library, Python would have no hint it needs to run it, and things would probably not work as intended.

To avoid this behaviour, all code that should only run when executing the module itself should be enclosed inside the so-called main statement:

if __name__ == "__main__":
    # Code here will not run when just importing the module.
theberzi
  • 2,142
  • 3
  • 20
  • 34
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section "Answer Well-Asked Questions", and therein the bullet point regarding questions which "have been asked and answered many times before". – Charles Duffy Jul 26 '19 at 20:11
0

Use the following block in all the files which are being imported.

 if __name__ == '__main__':
     functionCall()

This should fix the issue.

C. Fennell
  • 992
  • 12
  • 20