Title: [defaultdict] default_factory should accept a "key" default parameter (which can be passed my __missing__)
Type: Stage: resolved
Components: Extension Modules Versions: Python 3.7
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: namtt, rhettinger, steven.daprano
Priority: normal Keywords:

Created on 2017-05-20 02:38 by namtt, last changed 2017-05-20 06:12 by namtt. This issue is now closed.

Messages (4)
msg293992 - (view) Author: Nam (namtt) Date: 2017-05-20 02:38
currently default_factory does not accept any parameter. This made the default value generated by it constant among keys. If default_factory takes in key as the parameter, it should be able to generate default values based on key, which provide more flexibility to the class defaultdict.
msg293993 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2017-05-20 03:06
Take a look at the __missing__(key) method for the regular dict API to see if it meets your needs.  It is in the ``d[key]`` section at 

>>> class UpperDict(dict):
        def __missing__(self, key):
            return key.upper()

>>> d = UpperDict()
>>> print(d['tom'])
msg294007 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-05-20 05:51
I think this should be closed. For backwards compatibility, the defaultdict default_factory function must remain as it is. There is lots of code that uses something like `int` or `list` as the factory, and if the missing key was to be passed, the code would break.

As Raymond says, if you need the key passed to your factory, you can subclass dict and give it a __missing__ method.
msg294010 - (view) Author: Nam (namtt) Date: 2017-05-20 06:12
Sure, thanks Raymond and Steven for your thoughts.
Date User Action Args
2017-05-20 06:12:42namttsetstatus: open -> closed

messages: + msg294010
stage: resolved
2017-05-20 05:51:45steven.dapranosetnosy: + steven.daprano
messages: + msg294007
2017-05-20 03:06:42rhettingersetassignee: rhettinger

messages: + msg293993
nosy: + rhettinger
2017-05-20 02:38:07namttcreate