Skip to main content

Why `value or None` turns a JSON zero into `None`

Updated 1 min readMarkdown

In Python 3.12.16, value or None returned None for the integer 0 in the position.values array [0] from the EP-0080 paper-trading export. A report that treats None as missing data would display the recorded zero position as missing. EP-0080 paper-trading record

This example uses the array from assets/trade-reviews/EP-0080/case.json and runs both expressions from the recorded test.

import json
value = json.loads('[0]')[0]
print(value or None)
print(None if value is None else value)

The recorded run printed the following output.

None
0

Python treats integer zero as false in a Boolean context, so value or None returns its right operand, None. The identity test value is None is false for 0, so the conditional expression returns 0. If you only need to pass the field through, use value directly. Use value is None when a branch should run only for None.

The example reads the array’s first element before evaluating either expression. The recorded test covered an existing array whose first element was an integer zero. Missing fields, empty arrays, and an explicit JSON null were outside the test.

1 view

About the author

No comments yet. Be the first to comment.