Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Implicit conversion of object to str?

Given the following code

class A:
  def __init__(self ):
    self.b = B()

  def __repr__(self):
    #return "<A with {} inside>".format( self.b )
    #return "<A with " + repr(self.b) + " inside>"
    return "<A with " + self.b  + " inside>" # TypeError: Can't convert 'B' object to str implicitly

class B:
  def __repr__(self):
    return "<B>"

a = A()
print(a)

I am wondering why B's __repr__ is not called when "adding" A's self.b to a string.

  • https://docs.python.org/3/reference/datamodel.html#object.repr
  • https://docs.python.org/3/reference/lexical_analysis.html#operators
like image 430
handle Avatar asked Aug 20 '15 14:08

handle


People also ask

Can t convert int object to str implicitly in Python?

This error message Can't convert 'int' object to str implicitly is clear, when concatenating strings with integers - you can't directly stick together a string and an integer. So, in order to resolve this problem, you have to explicitly parse the integer to a string by the str() built-in function .

How do you convert an object to a string in Python?

Use the str() class to convert an object to a string, e.g. result = str(my_object) . The str() class returns the string version of the given object.

Does Python do implicit conversion?

Implicit Type Conversion is automatically performed by the Python interpreter. Python avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.

What is Implicit Conversion in Python give an example?

Implicit data type conversion is done automatically by the python compiler without any involvement of the user. The compiler converts smaller data types into larger data types to prevent any loss of data, for example, conversion of int to float.


1 Answers

Concatenation doesn't cause self.b to be evaluated as a string. You need to explicitly tell Python to coerce it into a string.

You could do:

return "<A with " + repr(self.b)  + " inside>"

But using str.format would be better.

return "<A with {} inside>".format(self.b)

However as jonrsharpe points out that would try to call __str__ first (if it exists), in order to make it specifically use __repr__ there's this syntax: {!r}.

return "<A with {!r} inside>".format(self.b)
like image 64
SuperBiasedMan Avatar answered Sep 21 '22 05:09

SuperBiasedMan