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.

1
  • The import statement is only executed once in any case. Any further imports 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. Commented Aug 9, 2019 at 17:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.