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.
importstatement is only executed once in any case. Any furtherimports 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.