Search code examples
python

default class representation in REPL/Python


Where can I find the implementation of the default class representation in Python/REPL? Example:

>>> class Foo:
...   pass
>>> Foo
<class '__main__.Foo'>

Where is that whole string <class '__main__.Foo'> coming from? Is it defined in any PEP?

I've tried greping the source of https://github.com/python/cpython for <class but it gives me no useful results, and greping for class is pointless.


Solution

  • The string <class '__main__.Foo'> comes from the type.__repr__ method, which is implemented with the type_repr function in Objects/typeobject.c of CPython:

    PyObject *result;
    if (mod != NULL && !_PyUnicode_Equal(mod, &_Py_ID(builtins))) {
        result = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
    }