-2

I know this is a very common question, but the difference in here: I want to call a function (f1) that is in test.py file from new.py file, I know how to do it but my main question is that: in test.py file I have some program lines that are not inside functions, so when I call the f1 function in new.py and run the new.py file, the test.py file also is running, how can I fix this and prevent from running other lines in test.py? (in other words: how can I call a function in another file without running other lines that are in another file) thanks

  • It will be easier to understand if you can provide some snippets of your codes. – Vikash Kumar May 10 '22 at 09:45
  • put those top-level lines behind an `if __name__ == "__main__":` check to prevent them running when the code is only imported https://stackoverflow.com/q/419163/202168 – Anentropic May 10 '22 at 09:47

1 Answers1

1

It's simple: don't have any statements at the top level, outside of functions, class declarations and so on.

But of course, you still want to be able to execute those lines if you invoke test.py directly (not as an import). There is a common idiom in Python for this:

if __name__ == '__main__':
    # Top-level statements go here, and are only executed
    # if this file is invoked as a script

See What does if __name__ == "__main__": do for more information.

Thomas
  • 174,939
  • 50
  • 355
  • 478