str attributes for basic python object should be agnostic (original) (raw)

Python has the bizarre convention of having the following basic values:

True, False, None

instead of

true, false, null

That is in an of itself okay. But when it comes to serialisation (without the json module) using str(·) we get

"True", "False", "None"

I would like to suggest that the __str__-methods be rewritten for these basic values so that we instead get

"true", "false", "null"

MegaIng (Cornelius Krupp) April 22, 2025, 9:06am 2

No. These __str__ methods essentially delegate to __repr__, the same as for most other builtin objects.

__repr__ should, if possible, return python code that can be executed to get an equivalent object back.

Even ignoring these two facts, your proposal would probably break thousands, maybe millions of lines of code, especially doctests.

Monarch (Monarch) April 22, 2025, 9:14am 3

But there is no universal “serlization” format. For example, TOML doesn’t even have a null equivalent. The only thing Python can authoritatively and practically give you is its own representation.

raj-open (Raj) April 22, 2025, 9:20am 4

it is true that there is no 100% used-by-all standard. Nonetheless, the use of true, false, null is quite common:

Language true false null / equivalent
C 1 (or _Bool true) 0 (or _Bool false) NULL (macro)
C# true false null
C++ true false nullptr (C++11+) / NULL
Go true false nil
Java true false null
JavaScript true false null
PHP true false null
Python True False None
Rust true false None (via Option)
JSON true false null
TOML true false Not supported (omit or empty)
XML "true" (as text) "false" (as text) or omit
YAML true false null / ~ / empty

I guess it is “too late” but it would be nice if python would align itself more closely to other standards.

raj-open (Raj) April 22, 2025, 9:22am 5

Thanks, I hadn’t considered the use of __str__ to ensure that exec(·) / eval(·) work.

pitrou (Antoine Pitrou) April 22, 2025, 9:44am 6

Sidenote: this should have been posted to the Ideas category, IMHO.

storchaka (Serhiy Storchaka) April 22, 2025, 9:45am 7

Some languages accept also yes/no, on/off, t/f, etc as boolean values. And they may be case-insensitive, so True/False works too.

raj-open (Raj) April 22, 2025, 9:52am 8

You’re right. I guess python is not the starting point for this issue. What is probably needed is a global agnostic convention to which all language and format align themselves.

ncoghlan (Alyssa Coghlan) April 23, 2025, 12:27pm 9

That would be the JSON serialisation option that you mentioned in your initial post (regardless of the convention any language uses natively, they use true, false, and null in their JSON output, and expect it in their JSON input).