I propose the addition of a new conversion flag, !t, for Python f-strings to simplify the process of determining the type of a variable. Currently, if you want to include the type of a variable within a formatted string, you need to explicitly use f"{type(var)}". While this works, it can be made more concise and intuitive.
With the introduction of the !t conversion flag, users could easily obtain the type of a variable directly within an f-string. For example, instead of writing:
var = 42
print(f"The type of var is {type(var)}")
You could simply write:
var = 42
print(f"The type of var is {var!t}")
This small addition would enhance readability and reduce verbosity, making it easier for developers to quickly determine the type of variables within formatted strings. This change aligns with Python’s philosophy of simplicity and readability, providing a more straightforward way to access type information in debugging and logging scenarios.
I have already implemented this change in the C code base, and it functions as expected. You can review the implementation and test the changes at my repository: github. I believe this enhancement will be a valuable addition to Python.
!t is certainly more concise, but I don’t see how it is more intuitive.
The main job of a format string is to turn an object into a str for inclusion in a larger string, and since both str and repr exist for this purpose, it makes sense to provide syntax to select the desired conversion. type, however, is not such a function. It produces another non-str value that itself first needs to be converted to a string.
And finally, how often does one really need to need the type of a variable to justify adding special support for this particular function application?
Regardless of reasons, the effort was made regarding this specific functionality.
So just suggesting that it is a commonly used thing and possibly the next one in line if judged by number use cases.
From my experience len is a bit different. Majority of the time when I need it I have it already stored in some variable. But it might not be representative of average case though.
However, the issue with n/N/t/T is that there are permutations. E.g. __name__ or __qualname__? With __module__ prefix or not? Which separator? Why one, but not the other? And adding only 2 is pretty much doubling the number of available conversions.
I did some use case analysis in the past and as far as I remember the absolute number of use cases (although I think this might be next in line) is fairly low.
I suggested this in the past, but my conclusion was that the effort needed to push this forward is nowhere worth the benefit.
Formatting a type name was discussed in length in PEP 737. I suggest you to read the Rejected Ideas section. For example, it was proposed to add !t format and add type.__fully_qualified_name__ attribute.