0

For example,

import numpy
def text():
  ...

If there are a lot of import statements, I personally feel it seems better to import when it's needed, instead of importing all at the top of file. A major benefit of this is to make reader to understand the code easier and immediately know where the dependency is imported from.

Is there any side effect by doing this?

ling
  • 1,555
  • 3
  • 18
  • 24
  • 2
    This would go against the [PEP8 style guidelines](https://www.python.org/dev/peps/pep-0008/#imports): "Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants." – juanpa.arrivillaga Jan 31 '20 at 19:27
  • To add to @juanpa.arrivillaga answer, check this response out: [Should import statements always be at the top of a module?](https://stackoverflow.com/a/128577/1305461) – felipe Jan 31 '20 at 19:28

1 Answers1

1

The ultimate guidelines for best practice in python are in the PEP-8 style guide. In the guide section linked:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

In your question, you assert:

A major benefit of this is to make reader to understand the code easier and immediately know where the dependency is imported from

But actually the opposite is often true. If I open a .py file, I can quickly scan the first few lines to see ALL dependencies needed to run the script. If each is imported below, then suddenly I have to scan through the whole file to see if and when a library is required.Remember that code is looked at a handful of times when it's written, and usually just by the author or someone close to the author, but could be read 10X more times, by people unfamiliar with the script

G. Anderson
  • 5,815
  • 2
  • 14
  • 21