Accessing parent objects

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 26 06:01:22 EDT 2018


On Mon, 26 Mar 2018 10:02:23 +0200, Antoon Pardon wrote:

>> The trick is to use new-style classes that inherit from object, and
>> avoid the old-style classes that don't:
>>
>> # Good
>> class Spam(object):
>>     ...
>>
>> # Not so good
>> class Spam:
>>     ...
> 
> How good is that when almost all classes in the standard library are old
> style classes?

I'm glad you asked!

I presume you're talking about Python 2, since the standard library of 
Python 3 is 100% "new-style".

In Python 2, there are 76 new-style classes in the builtins, most of 
which can be subclassed:


py> import __builtin__ as builtins
py> sum(type(obj) is type for obj in builtins.__dict__.values())
76

As a very quick-and-dirty test, I counted classes in the stdlib that 
subclassed object:

[steve at ando python2.7]$ grep "class .*(object)" *.py | wc -l
55
[steve at ando python2.7]$ grep "class .*(object)" */*.py | wc -l
562

plus another 47 for list and int -- I didn't bother counting subclasses 
of dict, tuple, str, etc). So, in round figures, there are about 700 new 
style class in the Python 2.7 std lib.

As a similarly quick-and-dirty test, I counted old-style classes:


[steve at ando python2.7]$ grep "\Wclass .*[^\(\)]*:" *.py | grep -v -F "(" 
| wc -l
42
[steve at ando python2.7]$ grep "\Wclass .*[^\(\)]*:" */*.py | grep -v -F 
"(" | wc -l
365


I daresay that's an under-estimate, so let's double it to be safe.

So we have (in round figures) about 700 new-style classes versus 800 old-
style classes in Python 2.7.

I'm no mathematician[1] but that hardly seems like "almost all" old-style 
classes to me.

We can quibble about the exact numbers, and about which classes are the 
most commonly subclassed, and how many false positives there are from 
using grep, but however you look at it, it is clear that a significant 
portion of stdlib classes are new-style.





[1] Actually, I am.

-- 
Steve




More information about the Python-list mailing list