Many new python programmers don’t know what’s the difference between them:

import x and from x import y.

importers gain access to all the names assigned at the top level of a module’s file. These names are usually assigned to tools exported by the module —functions, classes, variables, and so on—that are intended to be used in other files and other programs. Externally, a module file’s names can be fetched with two Python statements, import and from, as well as the reload call.

lets say we are using the numpy library:

Example of using import x:

1
2
3
import numpy   # Run file; load module as a whole
arr = numpy.array([1,2,3]) # Use its attribute names: '.' to qualify
print(arr) # print [1 2 3]

Example of using from x import y:

1
2
3
from numpy import array   # Run file; load specific attribute
arr = array([1,2,3]) # Use name directly: no need to qualify
print(arr) # print [1 2 3]

You can actually use the built-in dir function to fetch a list of all attribute names inside a module.

1
2
import numpy as np
dir(np)

^You will be able to find an attribute called array, which is a function we used to create an array.

some of the names it returns are names you get “for free”: names with leading and trailing double underscores (X) are built-in names that are always predefined by Python and have special meaning to the interpreter, but they aren’t important at this point

Reference

Learning Python: Powerful Object-Oriented Programming, Chapter 3: How You Run Programs

import versus from: I should point out that the from statement in a sense defeats the namespace partitioning purpose of modules—because the from copies variables from one file to another, it can cause same-named variables in the importing file to be overwritten, and won’t warn you if it does. This essentially collapses namespaces together, at least in terms of the copied variables.

Because of this, some recommend always using import instead of from. I won’t go that far, though; not only does from involve less typing (an asset at the interactive prompt), but its purported problem is relatively rare in practice. Besides, this is something you control by listing the variables you want in the from; as long as you understand that they’ll be assigned to values in the target module, this is no more dangerous than coding assignment statements—another feature you’ll probably want to use!