Home > OS >  Subclasses of object class for Python in Linux command line
Subclasses of object class for Python in Linux command line

Time:07-11

A Python install on Linux identifies 187 subclasses of the object class through this query:

kali@kali:~$ python3 -c 'print(len("".__class__.__mro__[1].__subclasses__()))'

The same query in an IDLE shell identifies 342 subclasses, and in the IDE PyCharm only 217!

Can the user decide which subclasses are operative in a given environment, or are subclasses rigorously enforced by the vendor?

CodePudding user response:

When performing the check on various setups it seems your query is based on properties of the object class:

"".__class__.__mro__
(<class 'str'>, <class 'object'>)

Thus your query can be translated as:

len(object.__subclasses__())

Let's rephrase your question as: Why does the count of subclasses of the class object vary with respect to the context?

The key is: Your query literally counts the number of classes inheriting from the class object (read more about this specific class) at the moment of querying and this count definitely depends on your version of python, environment and imports.

For sure initialization of python in both cases are not equivalent as the number of objects inheriting from object are different.

For instance, defining a class depending - explicitly or not - on object is sufficient to change this count:

>>> len(object.__subclasses__())
282
>>> class A(object):
...    pass
...
>>> len(object.__subclasses__())
283
>>> class B:
...     pass
...
>>> len(object.__subclasses__())
284

Importing a package will indeed change this count as well:

>>> import pandas as pd
>>> len(object.__subclasses__())
712

Notice that it also depends on the environment. So basically it depends on the PYTHONPATH and installed modules that can be found in this path:

> activate base
(base) > python -c "print(len(object.__subclasses__()))"
202
(base) > activate test
(test) > python -c "print(len(object.__subclasses__()))"
139

So the answer is almost certainly because the IDLE your ran is not the same python version or it have not the same environment or it has different modules imported than the PyCharm IDE.

As pointed by @jasonharper IDLE might have imported python classes that does increase the count.

So of you need to keep this check you will have to fix the context to make it reproducible. You can use environments or containers with specific images for that. Or design another check that is more resilient.

  • Related