Home > Software engineering >  Question regarding Python namespaces and function imports: Is it preferable to import only the funct
Question regarding Python namespaces and function imports: Is it preferable to import only the funct

Time:01-25

So I don't recall where I heard this or read this, but I remember being instructed that it was best practice to import only the needed functions or classes from modules for several reasons.

We should do this

from my_module import (needed_function, NeededClass)
from numpy import (arange, nditer, ones, zeros, array ndarray)

needed_function()
NeededClass()

ones
arange(0,16).reshape(4,4)
#etc etc

rather than import the module and calling the needed functions

import my_module as mm
import numpy as np

mm.needed_function()
mm.NeededClass()

np.ones
np.arange(0,16).reshape(4,4)
#etc etc

I was told that the primary reason is that when module.function is called Python must search the local namespace for module then search the module's namespace for function, then continue. This must be done each time module.function is called and is potentially very time wasting (for large computations).

The contrasts with directly importing the function because then python only needs to search the local namespace once for that function, a much smaller task than searching a potentially very large namespace, such as numpy or scipy.

Is this correct?

CodePudding user response:

Some good answers: https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function

Personally for my use case, I'm creating an .exe that needs to be very portable and as small file size as possible. Because of that, I mostly import only single functions where possible.

  • Related