Python 3 introduced views (see this question). They were also backported to Python 2.7. I am currently in the process of subclassing dict
in a Python 2.7 application (though with the goal to port it to Python 3 as well). I was wondering if - and how - I could subclass the .viewitems()
and similar functions in such a way that they behave exactly like the original views.
Here is my intent: I have a dictonary like this:
data = my_subclassed_dict
data["_internal"] = "internal_value"
data["key"] = "value"
list(data.keys()) == ["key"]
That is, I filter everything stat starts with a "_"
. This works fine so far: For iterators I just yield
and for lists I use a list comprehension that filters undesired values. However, those items have no connection the dict
anymore (which is fine, it feels exactly like a dict). However, with both ways, this does not work:
keys = data.viewkeys()
"key" in keys
del data["key"]
"key" not in keys # This is False !
The last part does not work because there is no reference to the original keys, so Python won't notice.
So: Is there a simple way to achieve this (without re-implementing all of the logic!)?
This is more of a question out of interest as I don't see it to apply that much in my scenario.