1

So where should I put import statements which are only used by main function, at the top of it's body or if __name__ == "__main__": ?

beardeadclown
  • 327
  • 2
  • 14
  • The presence of an `if __name__` block implies that the script might be imported. If it's imported, you probably need the imports to be run so that the code will work. – khelwood Sep 02 '21 at 11:47
  • @khelwood They are only used in main function. – beardeadclown Sep 02 '21 at 11:53
  • Then you could just import them in the main function, if the rationale is that you don't want the extra work of importing them when your script is imported. But it's probably unnecessary optimisation. – khelwood Sep 02 '21 at 11:57

1 Answers1

0

Import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.

Full explanation: How to Use the Python import Statement

Niv Dudovitch
  • 1,614
  • 7
  • 15