Counter in Collections Python Module

I ran into a really weird problem. I am trying to use the counter function in the collections module. However, I keep getting the same error message

AttributeError: 'module' object has no attribute 'Counter' 

I tried to use it before, and it worked fine, but now for some reason, when I import the “collection” module, it has a very limited number of attributes.

I tried:

 import collections # when calling Counter I would then use collections.Counter() import collections as collect # collect.Counter() 

For both, I keep getting the attribute error.

I also tried

 from collections import Counter 

And in this case, I got:

 ImportError: cannot import name Counter 

All of them are tested both in the ipython interface and through a script (without importing anything, just collections).

Any ideas?

+8
collections counter python-import importerror
source share
3 answers

The Counter class was added to the module in Python 2.7. Most likely you are using Python 2.6 or later. In the documentation for collections.Counter() :

New in version 2.7.

In python 2.5 or 2.6 use this backport .

+24
source share

When using pandas , the same problem occurred.

Reason : Counter is only supported in python2.7 and later and not available in earlier versions - the Counter class has been added to the collections package in Python 2.7 .


Solution 1 : As Martin Peters stated, use the return path.

Add counter.py to /lib64/python2.6/ - here collections.py is ./lib64/python2.6/collections.py Patch collections.py with:

 from counter import Counter 

Solution 2 : use the backport_collections package. The following patch (import statement) of the package in which you get an exception, for example, pandas in my case:

 from backport_collections import Counter 
+2
source share

You are probably using an old version of Python, the Counter class, as indicated in the documentation that was added in version 2.7.

+1
source share

All Articles