1

When I need to use numpy within a python function I'm defining, which method is correct/better/preferred/more pythonic?

Method 1

def do_something(arg):
    import numpy as np
    y = np.array(arg)

    return y

or

Method 2

import numpy as np
def do_something(arg):
    y = np.array(arg)

    return y

My expectation is that method 2 is correct because it does not execute the import statement every time the function is called. Also, I would expect that importing within the function only makes numpy available within the scope of that function, which also seems bad.

Chad
  • 1,434
  • 1
  • 15
  • 30
  • The `import` statement is only executed once in any case. Any further `import`s of the same package will have no effect. The convention is to put all the imported packages at the beginning of the file. Importing within a function may make sense in some special cases, such as defining some functionality that uses some optional dependency or reducing script loading time by lazily loading dependencies on demand. For example, I have used that in some scripts to validate input quickly and only load heavy dependencies if the input is valid. – jdehesa Aug 09 '19 at 17:22

1 Answers1

1

Yes method 2 is correct as is your explanation. Import in Python is similar to #include header_file in C/C++. Module importing is quite fast, but not instant, put the imports at the top. It is also not true that method 1 makes the code slow.

Sammit
  • 169
  • 1
  • 8