On Tue, Jan 21, 2020 at 09:01:29AM -0600, Karl O. Pinc wrote: > Understood. But you still might want to document, or even define in the > language, that you're outputting the shortest unambiguous > representation.
I'm not even sure I would want to do that. That would make it a language guarantee and force all implementations to follow. Jython and IronPython may prefer to follow the repr used by Java and .Net; if not those two implementations, other implementations might want to do something similar. > I guess I will advocate for _some_ specification built into Python's > definition. Otherwise everybody should _always_ build their own > formatter; lest they wake up one morning and find that int zero prints > as "+0". We're not talking about ints, we're talking about floats. There's only one reasonable way to print ints that everyone expects, and that doesn't including putting a spurious sign on zero. As far as I know, ints print the same in just about every single programming language that uses base ten Arabic-Hindu digits 0...9. It's kind of a universal. > > > I don't really care whether there's documentation for __str__() or > > > __repr__() or something else. I'm just thinking that there should > > > be some way to guarantee a well defined "useful" float output > > > formatting. > > > > https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting > > > > https://docs.python.org/3/library/string.html#format-string-syntax > > Thanks. For some reason nobody in #python pointed me to the 'g' format > type. That resolves my issue. > > Unfortunately, because 'g' can strip the trailing ".0" floats > formatted with it no longer satisfy the float->str->float > immutability property. I don't see why. Any string you get back from %g ought to convert back to a float without loss of precision, the trailing '.0' should not affect it. Can you give an example where it does? It seems to work for me. py> x = 94.0 py> float('%g' % x) == x True Do you care about having the shortest representation, or consistent representation? If you want a consistent representation, then I understand that %.17e is guaranteed to round-trip exactly for all floats (C doubles): py> '%.17e' % 94.0 '9.40000000000000000e+01' If you care about length, "94" is shorter than "94.0" and it still losslessly converts back to the float 94.0: py> '%.17g' % 94.0 '94' repr() will (I think) round trip, but it won't necessarily be the shortest, and it won't be consistent. -- Steven _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-le...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/WEHXLXEZ7PI5DOUEVCHQJ63NRBVWEMLC/ Code of Conduct: http://python.org/psf/codeofconduct/