Where can I find the dict_keys class?

Question:

How can I get a reference directly on the dict_keys class? Currently the only way I could find is by creating a temporary dict object and type-checking it.

>>> the_class = type({}.keys())
>>> the_class
<class 'dict_keys'>
>>> the_class.__module__
'builtins'
>>> import builtins
>>> builtins.dict_keys
AttributeError: module 'builtins' has no attribute 'dict_keys'
Asked By: wim

||

Answers:

That’s how you’re "supposed" to do it, though the only reason I’ve ever bothered is to fix a bug in Py 2.7 where dict_keys wasn’t a virtual subclass of collections.KeysView, and I used that technique to do what Py3 does by default.

When collections.abc (implemented in Python, not C) registers the type as a virtual subclass of collections.abc.KeysView, it does:

dict_keys = type({}.keys())
... many lines later ... 
KeysView.register(dict_keys)

because the class isn’t otherwise exposed at the Python layer. I figure if Python itself has no better way to accomplish the task, it’s probably the right way to do it. Of course, you could always borrow the fruits of Python’s labor:

# Can't use collections.abc itself, because it only imports stuff in
# _collections_abc.__all__, and dict_keys isn't in there
from _collections_abc import dict_keys

But given that _collections_abc is undocumented (aside from a link to the source code in the collections.abc documentation, which I doubt constitutes a binding contract to preserve it), I’d stick to dict_keys = type({}.keys()) (which doesn’t rely on any undocumented behaviors), or when you’re performing isinstance-based type-checking, use collections.abc.KeysView instead.

Answered By: ShadowRanger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.