0

I've consulted documentation and this question but confused how to move forward with these. I provide a brief recap before I ask my question.

Brief recap

1 - Everything in python is an instance of a class. This can be confirmed with using


x.__class__

where x can be anything!

2 - Every class is subclass of "object". This can be confirmed with


x.__class__.__mro__

where x can be anything!

3 - Every class itself (refer to point 1) is instance of a class called "type". This can be confirmed by

x.__class__.__class__

where x can be anything!

My Question

How can you implement such a logic?!

1- "type" itself is a class, so point 3 alone is confusing! "type", as a class, is an instance of itself!

type.__class__.__class__ == type

2- point 3 together with point 2 is also confusing! When you want to implement "type", you need "object" to be implemented to derive from it! But in order to have "object" as an instance, you need "type" to be implemented!

How such a thing possible to practically implement?!

object.__class__.__mro__[-1] == object

Ehsan Sh
  • 227
  • 2
  • 8
  • It's possible to implement it for example like this: https://github.com/python/cpython, or more specifically, like this: https://github.com/python/cpython/blob/main/Objects/typeobject.c – mkrieger1 Oct 28 '21 at 22:36
  • Thanks @mkrieger1 . So since I don't know C, I tried to find the python implementation. I referred to [this](https://www.pypy.org/); but couldn't find the github repo and specifically where this is implemented. If you kindly help me find it, I would read it and answer it here for others to refer to it later. – Ehsan Sh Oct 28 '21 at 22:53
  • You can't implement it in Python, that's exactly the issue, it's a hack written in C. Which makes sense after all – Bharel Oct 29 '21 at 01:09
  • Thanks @Bharel . But then how does [PyPy](https://www.pypy.org/) implement it?! I couldn't find the github repo! nor would I know where to find it! – Ehsan Sh Oct 29 '21 at 01:45
  • 1
    The reason you can't find a GitHub is because they use a [gitlab](https://foss.heptapod.net/pypy/pypy/-/blob/branch/default/pypy/objspace/std/typeobject.py). I do not know how the JIT in pypy works and what is the end output, but that's the type object. Do keep in mind that `__class__` is a descriptor, meaning it's just a regular function that can return whatever it wants, in this case the `tp_type` pointer IIRC. – Bharel Oct 30 '21 at 03:25

0 Answers0