0

I am trying to write my own functions/methods in a tools.py module for an ongoing project.

I need to import some modules like numpy for these methods, but am unsure of the best way to do this. Should I import within each method each time I call that function? Or in the tools.py script at the beginning? I do not always need all the functions in tools.py, and for example, don't always need numpy in the script where I call import tools. I would like my code to be as efficient as possible.

I only found info that I need not import numpy if I do not call it directly in a specific script.

Nimantha
  • 6,405
  • 6
  • 28
  • 69

3 Answers3

1

You could allways import only specific functions or classes of a module, i.e.:

from tools import myfunction

Further it is correct that you dont import numpy if you dont need it. However as far as my experience goes, imports of imports are not available in the current script.

This means when your tools.py contains the import numpy, and you load your tools in another script main.py, numpy (i.e. numpy.array()) wont be available in main.py. You would need to import it there as well.

However you can also import modules inside of functions to reduce the visibility and initial start up time of a script, see also this link

Some general performance tips are also provided here

This said, in general modern computers have evolved so far that imo in most use cases you dont need to worry to much about performance

Björn
  • 1,610
  • 2
  • 17
  • 37
1

I could be wrong, but I'm pretty sure importing a module loads the entire thing whether you use import sys or from sys import argv. So, importing numpy into the tools module will make the entire numpy module available to the tools module and, though not directly callable, wherever the tools module is imported into. I've only seen imports within a function to achieve optional library support. I hadn't heard of it being done for the sake of efficiency nor performance.

These links may help further:

Should import statements always be at the top of a module? https://softwareengineering.stackexchange.com/q/187403

alexako
  • 122
  • 7
0

You shouldn't by importing numpy at every method call. This should only be done once at the start of your script. If you don't want to import the entire module in tools.py, just import specific submodules you need from the library:

from numpy import submodule1, submodule2