0

Possible Duplicate:
Python import coding style

When I write some code that requires an import, and the import is only introduced by the bit of code I'm currently writing, should I:

Stick the import at the top of the file where it is made clear that to make this module work it needs these imports, yet the import is detached from the usage and should the need be removed later the module may still import stuff it doesn't ever actually use, or

Keep the import with the code that uses it immediately thereafter so it is obvious what the import is used to do and whence it can be safely removed, but risk importing the same libs multiple times and make it hard to work out what libs are required to make the module work.

Best practice?

Put the import at the top? Or put it where it gets used?

Community
  • 1
  • 1
John Mee
  • 50,179
  • 34
  • 152
  • 186
  • and http://stackoverflow.com/questions/296270/which-is-more-efficient-in-python-standard-imports-or-contextual-imports or http://stackoverflow.com/questions/6025635/python-speed-up-imports – Ben Jun 01 '12 at 13:00

1 Answers1

4

Import_Statement_Overhead from the Python wiki states:

"import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances."

I follow general stylistic conventions and put all of my import statements at the top of the program. PEP 8 states re imports:

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

Levon
  • 138,105
  • 33
  • 200
  • 191