Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'collections' is not defined" occurs when we use
collections module without importing it first. To solve the error, import
collections module before using it -
Here is an example of how the error occurs.
# ⛔️ NameError: name 'collections' is not defined d = collections.OrderedDict() d['name'] = 'Alice' d['age'] = 30
To solve the error, we have to import the collections module.
# ✅ import collections module first import collections d = collections.OrderedDict() d['name'] = 'Alice' d['age'] = 30 print(d) # 👉️ OrderedDict([('name', 'Alice'), ('age', 30)])
Even though the
collections module is in the Python standard library, we still
have to import it before using it.
collectionsbecause module names are case-sensitive.
Also, make sure you haven't imported
collections in a nested scope, e.g. a
function. Import the module at the top level to be able to use it throughout
An alternative to importing the entire
collections module is to import only
the functions and classes that your code uses.
from collections import OrderedDict d = OrderedDict() d['name'] = 'Alice' d['age'] = 30 print(d) # 👉️ OrderedDict([('name', 'Alice'), ('age', 30)])
The example shows how to import the
OrderedDict class from the
Instead of accessing the members on the module, e.g.
we now access them directly.
This should be your preferred approach because it makes your code easier to read.
import collections, it is much harder to see which classes or functions from the
collectionsmodule are being used in the file.
Conversely, when we import specific classes, it is much easier to see which
classes and functions from the
collections module are being used.
collections module implements classes and functions that provide
alternatives to Python's general purpose built-in containers (
You can view all of the classes and functions the
collections module provides
by visiting the