'Python/numpy/scipy best practices regarding partial import of some functions into the global namespace

It has long since become standard practice, when working with numpy in Python, to never type from numpy import *. Instead you should import numpy as np and then prepend the np._______ namespace to things.

An alternative style usage, which is also extremely common, is to hand-import a few functions into the global namespace as you need them, such as from numpy import exp, log or whatever. This seems to be generally accepted to the point that almost every single example from the official scipy documentation uses this style. For instance, looking at some examples from scipy's "sparse" documentation and scipy's "integrate" documentation we have:

from scipy.sparse import lil_matrix
from scipy.sparse.linalg import spsolve
from numpy.linalg import solve, norm
from numpy.random import rand
from numpy import array
from numpy import sqrt, sin, cos, pi
from scipy.integrate import quad, dblquad
from scipy.integrate import solve_ivp
from scipy.special import gamma, airy
...

and so on.

I would like to know if there are any style guidelines regarding this sort of usage. For starters, I guess this is acceptable to do as long as we aren't shadowing built-ins? For instance, even in just the above examples, which are just little toy examples for the documentation, there are 15 numpy functions being imported into the global namespace. In any reasonably-sized program, this list will easily grow to 5x-10x that number as the program develops. On the other hand, as long as you aren't shadowing built-ins, the biggest side-effect will be a large set of import statements in the header. So is that what people do, then?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source