YoomarXD
YoomarXD

Reputation: 125

How to print __repr__ in a Python3 file? (not in shell)

I know that in Python Shell when you type >>> object it shows the object.__repr__ method and if you type >>> print(object) it shows the object.__str__ method.

But my question is, is there a short way to print __repr__ while executing a Python file?

I mean, in a file.py if I use print(object) it will show object.__str__ and if I just type object it shows nothing.

I have tried using print(object.__repr__) but it prints <bound method object.__repr__ of reprReturnValue>

Or is this impossible?

Upvotes: 7

Views: 8469

Answers (4)

Anthon
Anthon

Reputation: 76599

If you just want to print the representation and nothing else, then

print(repr(object))

will print the representation. Where your invocation went wrong were the missing parentheses, as the following works as well:

print(object.__repr__())

If however you want this to be part of more information and you are using string formatting, you don't need to call repr(), you can use the conversion flag !r

print('The representation of the object ({0!r}) for printing,'
      ' can be obtained without using "repr()"'.format(object))

Upvotes: 7

elethan
elethan

Reputation: 16993

Try:

print(some_object.__repr__())

__repr__ needs to be called before you print it since it is a method unlike attributes such as __file__, __name__, etc., which do not need to be called (and cannot, for that matter). The same is true for the __str__() method: you need to call it with - some_object.__str__(), not some_object.__str__.

I assumed that the OP was referring to a general object with the word object, rather than the actual Python object called object, so I have used the variable name some_object instead. As was pointed out in the comments, if you literally do object.__repr__() this will raise an exception since __repr__() must be called on the instance (i.e., object().__repr__() will work).

Upvotes: 0

Useless
Useless

Reputation: 67733

You can use the old backticks

print(`object`)

in Python 2, or

print(repr(object))

in both Python 2 & 3

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308158

Just use repr(object).

print(repr(object))

Upvotes: 1

Related Questions