Jan
Jan

Reputation: 5162

Conventions for 'import ... as'

Typically, one uses import numpy as np to import the module numpy.

Are there general conventions for naming?

What about other modules, in particular from scientific computing like scipy, sympy and pylab or submodules like scipy.sparse.

Upvotes: 10

Views: 5032

Answers (1)

Fred Foo
Fred Foo

Reputation: 363687

SciPy recommends import scipy as sp in its documentation, though personally I find that rather useless since it only gives you access to re-exported NumPy functionality, not anything that SciPy adds to that. I find myself doing import scipy.sparse as sp much more often, but then I use that module heavily. Also

import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx

You might encounter more of these as you start using more libraries. There's no registry or anything for these shorthands and you're free to invent new ones as you see fit. There's also no general convention except that import lln as library_with_a_long_name obviously won't occur very often.

Aside from these shorthands, there's a habit among Python 2.x programmers to do things like

# Try to import the C implementation of StringIO; if that doesn't work
# (e.g. in IronPython or Jython), import the pure Python version.
# Make sure the imported module is called StringIO locally.
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

Python 3.x is putting an end to this, though, because it no longer offers partial C implementations of StringIO, pickle, etc.

Upvotes: 12

Related Questions