Author bar.harel
Recipients aganders3, aviramha, bar.harel, benjamin.peterson, bukzor, georg.brandl, jmillikin, levkivskyi, miss-islington, pitrou, rhettinger, serhiy.storchaka
Date 2022-01-14.14:40:46
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1642171247.3.0.805812720473.issue46376@roundup.psfhosted.org>
In-reply-to
Content
Up until now, trying to distinguish between actual sequences and mappings in C-API was a pain. Same methods are implemented in customer user classes, and the ABCs could have either been registered dynamically or had an appropriate __subclasshook__. On top of that, making the same checks as isinstance regarding the whole ABC and __mro__ chain would considerably slow down the code.

The new tp_flags are set in both registered abc classes, and subclasses of the appropriate types. As tp_flags exists, we don't even need to account for tp_as_mapping and tp_as_sequence. According to the docs "if such a flag bit is clear, the type fields it guards must not be accessed and must be considered to have a zero or NULL value instead.". User made classes that don't inherit from the Sequence and Mapping ABCs are not considered either, and there is no __subclasshook__ for these ABCs so inheritance is fully enforced.

As we cover builtins, c-extension classes and user-made Python classes, checking tp_flags is guaranteed to be accurate for distinguishing between mapping and sequence types, and would be as fast as a pointer dereference can be.

Modifying the current PySequence_Check and PyMapping_Check might be a breaking change, especially on a C-API level. However one can argue that checking for a mapping and expecting a failure on user-made mappings counts as a bug. Having them accurately return the correct type in a fast manner using tp_flags is therefore an acceptable breaking change.
History
Date User Action Args
2022-01-14 14:40:47bar.harelsetrecipients: + bar.harel, georg.brandl, rhettinger, pitrou, benjamin.peterson, jmillikin, bukzor, aganders3, serhiy.storchaka, levkivskyi, miss-islington, aviramha
2022-01-14 14:40:47bar.harelsetmessageid: <1642171247.3.0.805812720473.issue46376@roundup.psfhosted.org>
2022-01-14 14:40:47bar.harellinkissue46376 messages
2022-01-14 14:40:46bar.harelcreate