Title: defaultdict.get does not default to initial default but None
Type: behavior Stage: resolved
Components: Documentation Versions: Python 3.2, Python 3.3, Python 2.7
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, joern, mark.dickinson, python-dev
Priority: normal Keywords:

Created on 2012-01-27 10:50 by joern, last changed 2012-01-27 14:14 by python-dev. This issue is now closed.

Messages (3)
msg152083 - (view) Author: Jörn Hees (joern) * Date: 2012-01-27 10:50
I wanted to create a "function registrar" d using a defaultdict. The library that this registrar is passed to expects it to return functions taking 3 args. Now if the first call is d.get(x) it seems that in contrast to d[x] the default arg of get is returned (None) instead of the defaultdicts default. If i call d[x] first and then d.get(x) i get what i expected.


In [1]: def foo(a,b,c):
   ...:     return (a,b,c)

In [2]: from collections import defaultdict

In [3]: d = defaultdict(lambda:foo)

In [4]: d.get(1)

In [5]: d[1]
Out[5]: <function foo at 0x1015a2ed8>

In [6]: d.get(1)
Out[6]: <function foo at 0x1015a2ed8>

In [7]: d.get(2)(1,2,3)
TypeError                                 Traceback (most recent call last)

/Users/joern/<ipython console> in <module>()

TypeError: 'NoneType' object is not callable

In [8]: d[2](1,2,3)
Out[8]: (1, 2, 3)

In [9]: d.get(2)(1,2,3)
Out[9]: (1, 2, 3)

I'm not sure this is the desired behavior, but it wasn't quite what i expected from a dictionary with a default.
If it is the desired behavior the documentation of defaultdict should include an explanation what happens.
msg152087 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-01-27 12:18
It's certainly intentional behaviour:  all the defaultdict does is provide a __missing__ method.  And as explained in

"No other operations or methods invoke __missing__()."

So it looks to me as though this issue should be either a doc issue, or a feature request for 3.3.  Reclassifying as a doc issue.
msg152096 - (view) Author: Roundup Robot (python-dev) (Python triager) Date: 2012-01-27 14:14
New changeset 089a086252fc by Benjamin Peterson in branch '3.2':
note that get() is not affected by default_factory (closes #13887)

New changeset 26612ad451ad by Benjamin Peterson in branch 'default':
merge heads (#13887)

New changeset b2db66bc8e7f by Benjamin Peterson in branch '2.7':
note that get() is not affected by default_factory (closes #13887)
Date User Action Args
2012-01-27 14:14:44python-devsetstatus: open -> closed

nosy: + python-dev
messages: + msg152096

resolution: fixed
stage: resolved
2012-01-27 12:18:28mark.dickinsonsetversions: + Python 3.2, Python 3.3
nosy: + mark.dickinson, docs@python

messages: + msg152087

assignee: docs@python
components: + Documentation, - Extension Modules, Library (Lib)
2012-01-27 10:50:03joerncreate