Title: Proposed class for collections: dynamicdict
Type: enhancement Stage: resolved
Components: ctypes Versions: Python 3.9
Status: closed Resolution: out of date
Dependencies: Superseder:
Assigned To: Nosy List: Steele Farnsworth, eric.smith, steven.daprano
Priority: normal Keywords:

Created on 2020-04-10 21:19 by Steele Farnsworth, last changed 2020-04-11 01:30 by steven.daprano. This issue is now closed.

Messages (4)
msg366157 - (view) Author: Steele Farnsworth (Steele Farnsworth) Date: 2020-04-10 21:19
I have implemented a class in the C code of the collections module which has similar behavior to the defaultdict class. This class, dynamicdict, supplies values for keys that have not yet been added using a default factory callable, but unlike defaultdict, the missing key itself is passed to the callable. This code can be seen here:

While this does introduce a lot of redundant code, I'm not sure how it could be done without copying the implementation of the defaultdict class and adjusting how the default factory is called. For example, I don't believe that it's possible to support both behaviors within the defaultdict class without breaking backwards compatibility or adding another parameter to the constructor for the defaultdict class.

I would be happy to further explain the concept, implementation, potential use cases, or anything else that might work towards the adoption of this feature.
msg366158 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-04-10 21:58
You probably want to bring this up on the python-ideas mailing list for discussion. Features like this typically get discussed there first.
msg366159 - (view) Author: Steele Farnsworth (Steele Farnsworth) Date: 2020-04-10 22:03
Thank you, I have done so.
msg366174 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-04-11 01:30
This feature is already provided by just supplying a `__missing__` dunder:

py> class MyDict(dict):
...     def __missing__(self, key):
...             return "The key is {}".format(key)
py> d = MyDict()
py> d[1234]
'The key is 1234'

I'm closing this ticket, but if the discussion on Python-Ideas reaches consensus that your class is necessary, feel free to re-open it.
Date User Action Args
2020-04-11 01:30:21steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg366174

resolution: out of date
stage: resolved
2020-04-10 22:03:55Steele Farnsworthsetmessages: + msg366159
2020-04-10 21:58:12eric.smithsetnosy: + eric.smith
messages: + msg366158
2020-04-10 21:19:46Steele Farnsworthcreate