18

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

Alex Caseiro
  • 403
  • 1
  • 4
  • 9
  • Won't the import only happen once at the first call? – EdChum Nov 04 '16 at 09:52
  • 1
    see http://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times – EdChum Nov 04 '16 at 09:57
  • 3
    Python does not actually import a module that it has already imported (unless you force it to do so with the `reload` function), so you can safely put a `import some_module` statement into every module of your program that needs access to the names defined in `some_module`. – PM 2Ring Nov 04 '16 at 09:58
  • 4
    Thanks for the answers. Since the modules are not imported multiple times, then writing the import statement in each file only has the disadvantage of typing a bit more, but it has the advantage that when recycling the module, it won't be forgotten. cool :) – Alex Caseiro Nov 04 '16 at 10:03

1 Answers1

12

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

Community
  • 1
  • 1
SiGm4
  • 284
  • 1
  • 2
  • 10