Skip to content

Module 14 · Python Modules and Packages — topic 4 of 13

Importing specific functions

from module import name: importing selected functions, classes and constants, multi-line imports, avoiding name clashes and shadowed built-ins, and why star imports are discouraged.

Beginner 8 min read·Lesson 212 of 306 in Python Programming

Learning objectives

  • Import selected names with from ... import
  • Recognise and avoid name clashes
  • Explain why from module import * is discouraged

Definition

from module import name1, name2 imports specific objects from a module and binds them directly in the current namespace, so they can be used without the module prefix.

Introduction

Writing math.sqrt everywhere is fine, but sometimes you only need one or two names. from math import sqrt lets you write sqrt(25) directly.

Why it matters

Selective imports make code shorter and show exactly which tools a file uses — but careless use can replace built-in functions or hide where a name came from.

Detailed explanation

from math import sqrt, pi imports only those names; the module itself is not bound (math.floor would be a NameError).

The whole module still runs and is cached in sys.modules; from-import only controls which names you get.

Long import lists can be wrapped in parentheses across several lines.

Imported names can clash with your own names or with built-ins. from math import pow replaces the built-in pow, which accepts a third argument that math.pow does not.

from module import * imports all public names (or those in __all__). It hides where names come from and can silently overwrite others, so avoid it outside interactive sessions.

Use module imports (import json) when you use many names or when the module name adds clarity (json.loads is clearer than loads).

Import specific names when you use a few of them often and their names are unambiguous (from pathlib import Path).

Syntax

Python
from math import sqrt, pi
from collections import (
Counter,
defaultdict,
)
print(sqrt(25), pi)
  • Imports names, not the module.
  • Parentheses for long lists.
  • Avoid star imports.

Code examples

Selected names

Python
from math import sqrt, pi
print(sqrt(25), round(pi, 2))
Output
5.0 3.14

Shadowing a built-in

Python
print(pow(2, 3, 5)) # built-in pow: (2 ** 3) % 5
from math import pow
try:
pow(2, 3, 5)
except TypeError as e:
print("math.pow:", e)
Output
3
math.pow: pow expected 2 arguments, got 3

More examples

Several tools from one module

Python
from collections import (
Counter,
defaultdict,
namedtuple,
)
words = "to be or not to be".split()
print(Counter(words).most_common(2))
groups = defaultdict(list)
for w in words:
groups[len(w)].append(w)
print(dict(groups))
Point = namedtuple("Point", "x y")
print(Point(2, 3))
Output
[('to', 2), ('be', 2)]
{2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']}
Point(x=2, y=3)

Step-by-step explanation

  • The parenthesised import lists three classes, one per line, which keeps diffs tidy.
  • Each name is used directly without the collections prefix.
  • The names are distinctive, so it's still clear where they come from.

Expected output

Running “Several tools from one module” prints exactly:

TextOutput
[('to', 2), ('be', 2)]
{2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']}
Point(x=2, y=3)

Practical applications

  • from pathlib import Path and from datetime import date are very common.
  • from typing import Optional in type-annotated code.

Best practices

  • Import specific names you use often.
  • Keep module imports when the prefix adds clarity.
  • Never use star imports in modules.

Common mistakes

Star imports

Avoid

from math import *
from cmath import * # silently replaces sqrt, etc.

Prefer

import math
import cmath

Later star imports overwrite earlier names without warning.

Important notes

  • from module import name binds the object at import time; reassigning module.name later doesn't change your copy.

Key takeaways

  • from m import a, b binds names directly.
  • Watch for clashes with built-ins and your own names.
  • Avoid from m import *.

Try it yourself

  1. 1
    Rewrite a script that uses math.sqrt, math.pi and math.floor to import just those names.
  2. 2
    Show how from math import * changes the behaviour of pow.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions cover the “Python Modules and Packages” module. Answers and explanations are revealed after you submit.

  • ModerateWhat happens the second time a module is imported in the same program?
  • ModerateCode under if __name__ == "__main__": runs when…
  • ModerateWhat is printed?
Practise this module