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.
8 Likes
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.
3 Likes
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)
<tag xsi:nil="true"/>
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.
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.
1 Like
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.
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).
2 Likes