CodeBlanks Logo Icon CodeBlanks

from import

Learn selective imports with from x import y.

from import

from ... import takes only a specific item from a module. That item can now be used without the module name:

from math import sqrt
print(sqrt(16))  # 4.0

Here only sqrt is taken; there is no need to write math.sqrt. But since the math name is not loaded, math.pi is not available.

This is handy for calling a few frequently used items by short names.

Advantage and risk of from import

from math import sqrt shortens code. But from math import * loads everything — this is dangerous because it can cause name clashes:

# risky
from math import *
# where did sqrt come from? log?

Star imports hide which name comes from which module. They should be avoided in large projects. Instead, importing only the needed items by name is safer.

Good style: from math import sqrt, pi.

Practice from math import sqrt and pi

Write from math import sqrt, pi. Then write print(sqrt(16), pi).

Starter code

main.py
# take sqrt and pi from the math module
# print both together

Sample solution

main.py
from math import sqrt, pi
print(sqrt(16), pi)

Expected output

4.0 3.141592653589793

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the from import pattern

Question
from math ____ sqrt
print(sqrt(16))
Answer
from math import sqrt
print(sqrt(16))

Explanation: from math import sqrt takes only sqrt.

2 Match from import

Term Meaning
from math import sqrt Takes one item
sqrt(16) Direct call
import * Dangerous
from math import pi, sqrt Multiple items

3 After from math import sqrt, what does math.sqrt(16) do?

  • Raises NameError Correct answer
  • Works
  • Raises TypeError
  • Raises ImportError

Explanation: from math import sqrt takes only sqrt; the name math is not loaded.

All lessons in Beginner