As you experienced, there is some magic going on. However, it is not that every item is just being converted to string before formatting.
The TypeError explains what Python is trying to do: It is trying to call the __format__
method of your tuple. But it fails because tuple.__format__
does not expect a >
argument. If you were to fine-tune the formatting of your own class, you could do something like this:
class MyType:
def __init__(self, value):
self.value = value
def __format__(self, format_spec):
return f"this is the value {self.value} formatted against {format_spec}"
if __name__ == '__main__':
d = MyType(6)
print(f"{d:>10}")
Output:
this is the value 6 formatted against >10
So it would be up to your own MyType.__format__
to generate and return a string according to the format_spec
.
One native Python type that has a __format__
method that deals with a format_spec
like >10
would be the string class. That is the reason f"{str((1,2,3)):>10}"
works.
What you could do instead would be to use the !
marker to convert the tuple to string - this is equivalent to using str()
but less verbose:
f"{(1,2,3)!s:>10}"
Output:
' (1, 2, 3)'
With one space added to the left as wanted.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…