Why are set methods like .intersection() not supported on set-like objects?

拈花ヽ惹草 提交于 2019-12-02 06:38:14

dict views only guarantee the API of collections.abc.Set, not to be equivalent to set itself:

For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

So they're not claiming to match set, or even frozenset, just collections.abc.Set collections.abc.Set doesn't require any of the named methods aside from isdisjoint (which has no operator equivalent).

As for why collections.abc.Set doesn't require the named methods, it may be because they are somewhat more complex (most take varargs, and the varargs can be any iterable, not just other set-like things, so you can, for example, intersection with many iterables at once), and they may have wanted to limit the complexity required to implement new subclasses (especially virtual subclasses, that wouldn't inherit any of the methods collections.abc.Set might choose to provide).

All that said, I generally agree with your point that it seems needlessly inconsistent to omit the method forms. I'd recommend you open a bug on the Python bug tracker requesting the change; just because it only guarantees Set compatibility doesn't mean it can't do more.

The format should be

set.intersection(*others)

where other is any iterable. m.keys() is dict_keys not a set so that won't work.

set(m.keys()).intersection(n.keys())

will work :)

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