Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the output of repr useful?

Tags:

python

repr

I have been reading about repr in Python. I was wondering what the application of the output of repr is. e.g.

class A:
 pass

repr(A) ='<class __main__.A at 0x6f570>'

b=A()
repr(b) = '<__main__.A instance at 0x74d78>'

When would one be interested in '<class __main__.A at 0x6f570>' or'<__main__.A instance at 0x74d78>'?

like image 371
shaz Avatar asked Jan 11 '11 19:01

shaz


2 Answers

Theoretically, repr(obj) should spit out a string such that it can be fed into eval to recreate the object. In other words,

obj2 = eval(repr(obj1))

should reproduce the object.

In practice, repr is often a "lite" version of str. str might print a human-readable form of the object, whereas repr prints out information like the object's class, usually for debugging purposes. But the usefulness depends a lot on your situation and how the object in question handles repr.

like image 109
mipadi Avatar answered Sep 23 '22 03:09

mipadi


Sometimes you have to deal with or present a byte string such as

bob2='bob\xf0\xa4\xad\xa2'

If you print this out (in Ubuntu) you get

In [62]: print(bob2)
bob𤭢

which is not very helpful to others trying to understand your byte string. In the comments, John points out that in Windows, print(bob2) results in something like bob𤭢. The problem is that Python detects the default encoding of your terminal/console and tries to decode the byte string according to that encoding. Since Ubuntu and Windows uses different default encodings (possibly utf-8 and cp1252 respectively), different results ensue.

In contrast, the repr of a string is unambiguous:

In [63]: print(repr(bob2))
'bob\xf0\xa4\xad\xa2'

When people post questions here on SO about Python strings, they are often asked to show the repr of the string so we know for sure what string they are dealing with.

In general, the repr should be an unambiguous string representation of the object. repr(obj) calls the object obj's __repr__ method. Since in your example the class A does not have its own __repr__ method, repr(b) resorts to indicating the class and memory address.

You can override the __repr__ method to give more relevant information.


In your example, '<__main__.A instance at 0x74d78>' tells us two useful things:

  1. that b is an instance of class A in the __main__ namespace,
  2. and that the object resides in memory at address 0x74d78.

You might for instance, have two instances of class A. If they have the same memory address then you'd know they are "pointing" to the same underlying object. (Note this information can also be obtained using id).

like image 44
unutbu Avatar answered Sep 25 '22 03:09

unutbu