NameError: name 'collections' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'collections' is not defined in Python #

The Python "NameError: name 'collections' is not defined" occurs when we use the collections module without importing it first. To solve the error, import the collections module before using it - import collections.

nameerror name collections is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
# ✅ 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.

Make sure you haven't used a capital letter c when importing collections because 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 your code.

An alternative to importing the entire collections module is to import only the functions and classes that your code uses.

main.py
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 collections module.

Instead of accessing the members on the module, e.g. collections.OrderedDict, we now access them directly.

This should be your preferred approach because it makes your code easier to read.

For example, when we use an import such as import collections, it is much harder to see which classes or functions from the collections module 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.

The collections module implements classes and functions that provide alternatives to Python's general purpose built-in containers (dict, list, set and tuple).

You can view all of the classes and functions the collections module provides by visiting the official docs.

Conclusion #

The Python "NameError: name 'collections' is not defined" occurs when we use the collections module without importing it first. To solve the error, import the collections module before using it - import collections.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.