Skip to main content
Engineering LibreTexts

16.13: Importing with from

  • Page ID
  • Python provides two ways to import modules; we have already seen one:

    >>> import math
    >>> print math
    <module 'math' (built-in)>
    >>> print math.pi

    If you import math, you get a module object named math. The module object contains constants like pi and functions like sin and exp.

    But if you try to access pi directly, you get an error.

    >>> print pi
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'pi' is not defined

    As an alternative, you can import an object from a module like this:

    >>> from math import pi

    Now you can access pi directly, without dot notation.

    >>> print pi

    Or you can use the star operator to import everything from the module:

    >>> from math import *
    >>> cos(pi)

    The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.