Skip to main content
Engineering LibreTexts

16.13: Importing with from

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

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

    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
    3.14159265359
    

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

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

    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.

    • Was this article helpful?