Where should 'import' statement be put?

Erik Max Francis max at alcyone.com
Tue Apr 16 14:30:52 EDT 2002


gyromagnetic wrote:

> I was wondering what the 'best practice' is for locating 'import'
> statements. If I have a module comprising several classes, each of
> which has several functions, should the import statements be grouped
> - at the top of the module?
> - at the top of the classes in which they are relevant?
> - at the top of the functions in which they are relevant?
> 
> I believe imports are done only once regardless of the number of times
> the statement appears, but are there any other considerations here? I
> realize there may be scoping issues as well.

You're correct; importing modules is idempotent (only done once no
matter how many times an import statement is encountered), so this is
really a matter of style.

I nearly always put import statements at the top of the file, except in
the case where only one function uses them which may never get called. 
If, for instance, sys isn't used in the module proper, but _is_ used in
the main wrapper to scan for arguments, one might do something like:

	import StringIO
	import socket
	... etc. ...

	def main():
	    import sys
	    if len(sys.argv) ...

	if __name__ == '__main__': main()

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Nationalism is an infantile sickness.
\__/ Albert Einstein
    Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
 A new, virtual planet, every day.



More information about the Python-list mailing list