0

I'm curious how repr works. It can't be exactly

def repr_(x):
  return x.__repr__()

since that does not work on classes, namely

repr_(int)

causes an error since int's repr expects an int object as the first argument. I know that I can customize a class's repr by creating a metaclass with a desired __repr__, but I want to know how does Python's built in repr work? And how does it specifically handle the case of having a class passed into it.

Does it do something like a try catch where it first tries what my repr_ does and then looks up the MRO for other reprs? Or something else?

Enrico Borba
  • 1,877
  • 2
  • 14
  • 26

3 Answers3

0

Figured it out. If we inspect how Python internally computes repr, which we can see in the source file object.c, we can see that repr is essentially

def repr_(x):
  return x.__class__.__repr__(x)
Enrico Borba
  • 1,877
  • 2
  • 14
  • 26
0

import datetime

today=datetime.date.today()

print(repr(today))

for objects of classes, repr basically displays unambiguous output when obj call is their.

-1

Documentation https://www.cmi.ac.in/~madhavan/courses/prog2-2015/docs/python-3.4.2-docs-html/library/functions.html#repr

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.

Pravin
  • 677
  • 2
  • 7
  • 22
  • I understand what `repr` means, and what it's supposed to do. I understand how to customize `repr` for custom classes using a custom metaclass. I want to know how Python **internally** decides what `__repr__` to call. – Enrico Borba Apr 20 '19 at 17:29
  • https://stackoverflow.com/questions/5356773/python-get-string-representation-of-pyobject Check this out, this might help you. – Pravin Apr 20 '19 at 17:31