1

I encounter a problem while translating from python2 to python3 the following line:

fmap = defaultdict(count(1).next)

I changed count(1).next to next(count(1))

but get this error:

fmap = defaultdict(next(count(1))) TypeError: first argument must be callable or None

I guess this line intend to assign new default value each time. Do you have suggestions? Thanks

2 Answers2

1

The error is clear - the first argument to a defaultdict must be a callable (function for example, or class name), or None. This callable will be called in case a key does not exist to construct the default vale. On the other hand:

next(count(3))

will return an integer, which is not callable, and makes no sense. If you want the defaultdict to default to an increasing a number whenever a missing key is used then something close to what you have is:

>>> x=defaultdict(lambda x=count(30): next(x))
>>> x[1]
30
>>> x[2]
31
>>> x[3]
32
>>> x[4]
33
kabanus
  • 24,623
  • 6
  • 41
  • 74
0

The .next() method on iterators has been renamed in Python 3. Use .__next__() instead.

Code

fmap = defaultdict(count(1).__next__)

Demo

fmap["a"]
# 1

fmap["b"]
# 2

Note, defaultdict needs a callable argument, something that will act as a function, hence parentheses are removed, e.g. __next__.

pylang
  • 40,867
  • 14
  • 129
  • 121