multi-Singleton-like using __new__

Hrvoje Niksic hniksic at xemacs.org
Sat Feb 9 04:22:22 EST 2008


Matt Nordhoff <mnordhoff at mattnordhoff.com> writes:

> Steven D'Aprano wrote:
>> Except that using has_key() means making an attribute lookup, which takes 
>> time.
>
> I was going to say that, but doesn't 'in' require an attribute lookup of
> some sort too, of __contains__ or whatever?

It doesn't.  Frequent operations like __contains__ are implemented as
slots in the C struct describing the type.  The code that implements
"obj1 in obj2" simply executes something like:

    result = obj1->ob_type->tp_contains(obj2);  // intentionally simplified

User-defined types (aka new-style classes) contain additional magic
that react to assignment to YourType.__contains__ (typically performed
while the class is being built), to which they react by setting
"tp_contains" to a C wrapper that calls the intended function and
interprets the result.



More information about the Python-list mailing list