I'm writing a password management program that encrypts the passwords and saves the hashes to a document. Should I import before defining the functions, import in the functions they are used, or import after defining the functions but before running the functions. I'm trying to make my code as neat as possible. I'm currently importing passlib.hash, sha256_crypt, os.path, time. Sorry if it's not clear I'm kind of new and trying to teach myself. Any advice helps.
-
I saw that post I just wasn't sure at the time whether it was best to import modules before or after defining functions. – WorstPythonProgrammer Sep 24 '15 at 07:34
3 Answers
Typically imports come first in any design pattern I have seen. Imports > large scope variables > functions.

- 2,524
- 1
- 22
- 34
It's a good style to import in the very beginning of the code. So you have an overview and can avoid multiple imports.

- 3,313
- 2
- 19
- 27
-
Ok thanks, now what if I only use an module once for one function what do you recommend? – WorstPythonProgrammer Sep 24 '15 at 07:23
It's a common use to make all imports on top, mainly for readability: you shouldn't have to look around the whole code to find an import. Of course you have to import a symbol before you can use it.
Anyway in Python it's not always wrong to import inside functions or classes, this is because of the way Python actually interpret the import. When you import a module you are actually running it's code, that is, in most cases, just defining new symbols, but could be also to trigger some side effect; thus it sometimes make sense to import inside functions to make the imported code execute only on function call.

- 1,131
- 7
- 13