Search code examples
pythonfunctionpython-importcode-organization

Python - Does it matter if i import modules before or after defining functions? Newb Ques


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.


Solution

  • 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.