Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 995
Jan Avatar asked Feb 19 '13 14:02

Jan


1 Answers

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.

like image 67
Fred Foo Avatar answered Oct 03 '22 15:10

Fred Foo