Instead of importing an entire module and accessing everything through its name, this form binds specific names directly into the current scope, so you can call a function directly instead of prefixing it with the module name each time. It still runs the whole module's top-level code the first time, and caches it the same way a plain import does — it just changes which names end up directly accessible without a prefix. Using a wildcard imports every public name the module exposes, which is generally discouraged since it makes it unclear where any given name in your code actually came from.
1Understanding from ... import
Instead of importing an entire module and accessing everything through its name, this form binds specific names directly into the current scope, so you can call a function directly instead of prefixing it with the module name each time. It still runs the whole module's top-level code the first time, and caches it the same way a plain import does — it just changes which names end up directly accessible without a prefix. Using a wildcard imports every public name the module exposes, which is generally discouraged since it makes it unclear where any given name in your code actually came from.
Avoid a wildcard from-import in real code — it silently pulls in an unpredictable set of names, can shadow existing names in your file without warning, and makes it much harder for a reader, or an IDE, to tell where a given name is defined.
from math import sqrt, pi
print(sqrt(25))
print(pi)2Practical Example
Here is a real-world application of from ... import showing how it is used in production Python code.
from collections import defaultdict
counts = defaultdict(int)
for word in ["a", "b", "a", "c", "a"]:
counts[word] += 1
print(dict(counts))3Best Practices
Follow these guidelines when working with from ... import:
1. Use from module import specific_name for names you use frequently, to avoid repeating the module prefix everywhere
2. Avoid a wildcard from-import, since it obscures where each imported name actually comes from and risks silently overwriting existing names
3. List multiple imported names from the same module in one from-import statement instead of repeating separate import lines
Tip: Avoid a wildcard from-import in real code — it silently pulls in an unpredictable set of names, can shadow existing names in your file without warning, and makes it much harder for a reader, or an IDE, to tell where a given name is defined.
from math import sqrt, pi
print(sqrt(25))
print(pi)