Testing for an empty dictionary in Python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 24 03:39:06 CET 2008

On Sun, 23 Mar 2008 18:56:51 -0700, John Machin wrote:

>> Python knows the truth value of built-in types like dicts without
>> actually converting them to bools, or for that matter calling __len__
>> or __nonzero__ on them.
> What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to
> see if the built_in or extension type is a mapping (not just a dict)
> with a length method and if so calls it; similarly for sequences:
> 	else if (v->ob_type->tp_as_mapping != NULL &&
> 		 v->ob_type->tp_as_mapping->mp_length != NULL)
> 		res = (*v->ob_type->tp_as_mapping->mp_length)(v);
> 	else if (v->ob_type->tp_as_sequence != NULL &&
> 		 v->ob_type->tp_as_sequence->sq_length != NULL)
> 		res = (*v->ob_type->tp_as_sequence->sq_length)(v);
> Was that what you meant by "without ... calling __len__"?

What I meant was that the interpreter *didn't* do was lookup the name 
'__len__' via the normal method resolution procedure. There's no need to 
search the dict's __dict__ attribute looking for an attribute named 
__len__, or indeed any sort of search at all. It's a direct pointer 
lookup to get to mp_length.

I didn't mean to imply that Python magically knew whether a dict was 
empty without actually checking to see if it were empty. Apologies for 
being less than clear.

Also, since I frequently criticize others for confusing implementation 
details with Python the language, I should criticize myself as well. What 
I described is specific to the CPython implementation -- there's no 
requirement for other Python versions to do the same thing.


More information about the Python-list mailing list