user496934
user496934

Reputation: 4020

Should repr method in python always return string

I am new in Python. I have written the below code --

class AF:   
    def __repr__(self):
        return  {'name':1, 'age':44}

c = AF()        
print(c.__repr__())
print(repr(c))

When I run this, it is generating below error --

{'name': 1, 'age': 44}
print(repr(c))
TypeError: __repr__ returned non-string (type dict)

I read in Python documentation that repr should return string, OK got it, then why the first print statement ran successfully and printed the dictionary and the second print generated error? Shouldnot both the calls have failed? Trying to understand what is happening internally here.

Upvotes: 1

Views: 951

Answers (2)

Anwarvic
Anwarvic

Reputation: 12992

The __repr__ isn't just an ordinary method, it's a special built-in function that looks a lot like operators. These operators offer more than any method can offer.

When you called c.__repr__() you are calling the method part. On the other hand, when you called repr(c), you have called the operator. Same with __add__ operator. It can be called as a normal method a.__add__(b) or it can be used as an operator (which would require more assertions) like so a + b

Upvotes: 0

awarrier99
awarrier99

Reputation: 3855

It seems likely that the built-in repr function is performing an additional check on the return type of the instance's __repr__ function and raising an error if it is not a str as expected, whereas the __repr__ function when called directly, as any other function, can return any value

Upvotes: 3

Related Questions