Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python, do you need to import modules in each split file?

Tags:

python

module

I have a python script that is becoming rather long. Therefore, the functions defined in the rather large single script were written into individual files for easier maintenance and to easily share them between different main scripts.

In the single script, I import numpy and other modules at the top of the file. Now, if the function is written into a separate file, I need to import numpy in that separate file. I'd rather avoid that because with multiple functions it will end up importing numpy several times.

Can this be done? Thanks

like image 460
Alex Caseiro Avatar asked Nov 04 '16 09:11

Alex Caseiro


1 Answers

Yes it can be done, as described here: Python: Importing an "import file"

In short, you can put all imports in another file and just import that file when you need it.

Note though that each file needs to have numpy imported, one way or another.

EDIT:

Also read this: Does python optimize modules when they are imported multiple times? to understand how python handles multiple imports. Thanks to @EdChum

like image 171
SiGm4 Avatar answered Nov 15 '22 16:11

SiGm4