CreativelyChris
CreativelyChris

Reputation: 93

Python - Importing function from external file and global modules

In order to simplify my code, I have put various functions into external files with I load via:

from (external_file) import (function_name) 

...which works fine.

My question though has to do with other modules, such as cv2 or numpy - do I need those listed in my external file (as well as my main file) or is there a way to just list them in my main file?

Upvotes: 1

Views: 1342

Answers (1)

Blckknght
Blckknght

Reputation: 104712

Each file you put Python code in is its own module. Each module has its own namespace. If some of your code (in any module) uses some library code, it will need some way to access the library from the namespace it is defined in.

Usually this means you need to import the library in each module it's being used from. Don't worry about duplication, modules are cached when they are first loaded, so additional imports from other modules will quickly find the existing module and just add a reference to it in their own namespaces.

Note that it's generally not a good idea to split up your code too much. There's certainly no need for every function or every class to have its own file. Instead, use modules to group related things together. If you have a couple of functions that interoperate a lot, put them in the same module.

Upvotes: 4

Related Questions