3.8 Importing

We mention two issues with importing: circular imports and importing large third-party modules.

First, you must avoid circular imports. For example, suppose that the file SAGE_ROOT/devel/sage/sage/algebras/steenrod_algebra.py started with a line

from sage.sage.algebras.steenrod_algebra_bases import *
and that the file SAGE_ROOT/devel/sage/sage/algebras/steenrod_algebra_bases.py started with a line
from sage.sage.algebras.steenrod_algebra import SteenrodAlgebra
This sets up a loop: loading one of these files requires the other, which then requires the first, etc.

With this set-up, running Sage will produce an error:

Exception exceptions.ImportError: 'cannot import name SteenrodAlgebra' \
in 'sage.rings.polynomial.polynomial_element.\
Polynomial_generic_dense.__normalize' ignored
-------------------------------------------------------------------
ImportError                       Traceback (most recent call last)

...
ImportError: cannot import name SteenrodAlgebra
Instead, you might replace the import * line at the top of the file by more specific imports where they are needed in the code - e.g., the basis method for the class SteenrodAlgebra might look like this (omitting the documentation string):
    def basis(self, n):
        from steenrod_algebra_bases import steenrod_algebra_basis
        return steenrod_algebra_basis(n, basis=self._basis_name, p=self.prime)

Second, do not import at the top level of your module a third-party module that will take a long time to initialize (e.g., matplotlib). As above, you might instead import specific components of the module when they are needed, rather than at the top level of your file.

It is important to try to make from sage.all import * as fast as possible, since this is what dominates the Sage startup time, and controlling the top-level imports helps to do this.

See About this document... for information on suggesting changes.