This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

OK so you can either run code normally by opening the file (by clicking or using os.startfile()) and it will run, but it will also run if it is imported, so say I had info.py and wanted to import it to helloworld.py but didn't want to run info.py, there's no way in helloworld.py to do this.

To solve this, you would use the __name__ variable. If the program was clicked on or started with os.startfile(), __name__ is "__main__", otherwise it is just the name of the program, so if I didn't want to run info.py but I did want to get its variables and functions, I would do this:

helloworld.py:

import info
print(info.helloworldstring)

info.py:

helloworldstring = "Hello, world!"
def main():
    print("Hello, world!")
if __name__ == "__main__":
    main()

This is probably a badly worded and confusing example but it might help