Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception repr type: what does it means?

Tags:

python

Let's say I have this

try:
 #some code here
except Exception, e:
 print e
 print repr(e)

From this block of code I get

>>
>> <exceptions.Exception instance at 0x2aaaac3281b8>

Why don't I have any exception message and, moreover, what does second message means?

like image 1000
DonCallisto Avatar asked Dec 09 '22 04:12

DonCallisto


2 Answers

You have an exception which produces an empty str (i.e. str(e) is empty). Why that is cannot be known from the limited code you posted, you will have to look at the traceback to see where the exception came from.

As for repr(), that's intended to produce a string which may be ugly which allows reconstruction of the object, rather than pretty-printing. It's not what you want for printing exceptions.

like image 88
John Zwinck Avatar answered Dec 31 '22 01:12

John Zwinck


An Exception-derived object is thrown in # some code here. This object has a __str__ method that returns an empty string or spaces and no __repr__ method.

See Python Help.

class SomeClass(object):
  def __str__(self):
    # Compute the 'informal' string representation of an object.
    return 'Something useful'
  def __repr__(self):
    # Compute the 'official' string representation of an object. If at all possible, this should look like a valid
    # Python expression that could be used to recreate an object with the same value (given an appropriate environment).
    return 'SomeClass()'

o = SomeClass()

print o
print repr(o)

Outputs;

  Something useful
  SomeClass()
like image 36
owillebo Avatar answered Dec 31 '22 02:12

owillebo