Python和字典像对象 [英] Python and dictionary like object

查看:176
本文介绍了Python和字典像对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个python 3.1深度更新功能的字典(一个函数将递归更新父词典中的子词典)。

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).

但我认为,在未来,我的功能可能需要处理像字典这样的行为,但不是。此外,我想避免使用 isinstance 类型 (因为它们被认为是坏的,因为我可以在几乎每个Pythonista的博客上阅读)。

But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered bad, as I can read on almost every Pythonista's blog).

但是,鸭子打字是Python哲学的一部分,所以我如何检查一个对象是字典吗?

But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?

谢谢!

编辑:感谢所有的答案。以防万一,我可以在这个地方找到我编码的功能: http:// blog .cafeaumiel.com / public / python / dict_deep_update.py

Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : http://blog.cafeaumiel.com/public/python/dict_deep_update.py

推荐答案

查看(3.x中的新内容)集合模块中的抽象基类(ABC):

Check out the (new in 3.x) abstract base classes (ABC's) in the collections module:

http://docs.python.org/3.1/library/collections.html

我会考虑使用isinstance来检查映射如下所示:

I would consider checking with isinstance against Mapping like in the following:

>>> import collections
>>> isinstance({},collections.Mapping)
True

然后,如果你自己类似的类,使集合。映射其基础之一。

Then, if you make your own dict-like class, make collections.Mapping one of its bases.

另一个路由正在尝试捕捉字典操作的任何异常,但是随着递归,重新谈论,我宁愿检查基本类型,首先是处理一些字母或细节或其他dict成员或不在那里抛出异常。

The other route is trying and catching whatever exceptions for the dictionary operations, - but with the recursion you're talking about, I'd rather check against the base type first than handle figuring out what dict or subdict or other dict member was or was not there to throw an exception.

编辑添加:检查对照ABC而不是反对dict的好处是,同样的测试将适用于类似类的类,无论它们是否是子类,所以它更灵活,以防万一。

Editing to add: The benefit of checking against the Mapping ABC instead of against dict is that the same test will work for dict-like classes regardless of whether or not they subclass dict, so it's more flexible, just in case.

这篇关于Python和字典像对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆