[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] bpo-34595: How to format a type name?


On 09/13/18 14:08, Victor Stinner wrote:
> Le jeu. 13 sept. 2018 ? 16:01, Eric V. Smith <eric at trueblade.com> a ?crit :
>>> * Add !t conversion to format string
>>
>> I'm strongly opposed to this. This !t conversion would not be widely
>> applicable enough to be generally useful, and would need to be exposed
>> in the f-string and str.format() documentation, even though 99% of
>> programmers would never need or see it.
> 
> (I'm thinking aloud.)
> 
> In the Python code base, I found 115 lines using type(obj).__name__
> and 228 lines using obj.__class__.__name__.
[...]

"!t" is not a big improvement over ":T" and "type(obj)".

> I'm not sure if type(obj) or obj.__class__ should be used, but I can
> say that they are different: obj.__class__ can be overriden:
[...]
> 
> 
> Moreover, it's also possible to override the "type" symbol in the
> global or local scope:
[...]

I don't think either of those are problematic. If you override 
`__class__` or `type`, things will behave weirdly, and that's OK.

> One advantage of having a builtin formatter would be to always use
> internally the builtin type() function to get the type of an object,
> or not use "type()" in the current scope. The second advantage is to
> prevent the need of having to decide between type(obj) and
> obj.__class__ :-)
> 
> 
>> raise TypeError(f"must be str, not {obj!t}")
>>
>> Should be written as:
>> raise TypeError(f"must be str, not {type(obj)}")
[...]
> 
> Do you want to modify str(type) to return a value different than repr(type)?
> 
> Or maybe it's just a typo and you wanted to write f"{type(obj):T}"?

Yes, AFAIK that was a typo.

>> I think "T" is a good idea, but I think you're adding in obj vs
>> type(obj) just because of the borrowed reference issue in Py_TYPE().
>> That issue is so much larger than string formatting the type of an
>> object that it shouldn't be addressed here.
> 
> Right, that's a side effect of the discussion on the C API. It seems
> like Py_TYPE() has to go in the new C API. Sorry, the rationale is not
> written down yet, but Dino convinced me that Py_TYPE() has to go :-)

I'll be happy when we get rid of Py_TYPE and get to use moving garbage 
collectors... but now is not the time.
The API for "%T" should be "give me the type". The best way to do that 
might change in the future.


But at this point, we're bikeshedding. I think all the relevant voices 
have been heard.