How to wrap a python dict?

断了今生、忘了曾经 提交于 2021-02-04 15:08:39

问题


I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read.

Supposing I was to create an object to act like this; what methods would I need to implement?


回答1:


You can subclass the ABC (abstract base class) collections.Mapping (or collections.MutableMapping if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignment, pop, etc).

If you do so, then, as the docs I pointed to imply somewhat indirectly, the methods you need to implement are

__len__
__iter__
__getitem__

(for a Mapping) -- you should also implement

__contains__

because by delegating to the dict you're wrapping it can be done much faster than the iterating approach the ABC would have to apply otherwise.

If you need to supply a MutableMapping then you also need to implement 2 more methods:

__setitem__
__delitem__    



回答2:


In addition to what's already been suggested, you might want to take a look at UserDict.

For an example of a dict like object, you can read through django's session implementation, specifically the SessionBase class.




回答3:


I think it depends on which methods you use. Probably __getitem__, __setitem__, __iter__ and __len__ as most things can be implemented in terms of those. But you'll want to look at some use cases, particularly with __iter__. Something like this:

for key in wrapped_dictionary:
   do_something(wrapped_dictionary[key])

...is going to be slow if you hit the data source on each iteration, not to mention that it might not even work if the data source is changing out from under you. So you'll want to maybe throw some sort of exception there and implement iteritems as an alternative, loading all the key-value pairs in one batch before you loop over them.

The Python docs have item listings where you can look for methods and use-cases.



来源:https://stackoverflow.com/questions/3385269/how-to-wrap-a-python-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!