Skip to content

Commit

Permalink
Define IonPyBool as Distinct Type (#258)
Browse files Browse the repository at this point in the history
This change defines IonPyBool as it's own sub-class of int instead of
as an alias of IonPyInt.

Doing so removes the potential confusion around the python type and
__repr__ which could make Ion Booleans appear as Ion Ints.

gh issue: #88
  • Loading branch information
rmarrowstone committed Apr 5, 2023
1 parent 3c62e05 commit 56cf39a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
14 changes: 12 additions & 2 deletions amazon/ion/simple_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,23 @@ def __init__(self, *args, **kwargs):
return IonPyValueType


IonPyInt = _ion_type_for('IonPyInt', int)
IonPyBool = IonPyInt
IonPyInt = _ion_type_for('IonPyInt', int, IonType.INT)
IonPyFloat = _ion_type_for('IonPyFloat', float, IonType.FLOAT)
IonPyDecimal = _ion_type_for('IonPyDecimal', Decimal, IonType.DECIMAL)
IonPyText = _ion_type_for('IonPyText', str)
IonPyBytes = _ion_type_for('IonPyBytes', bytes)

# All of our ion value types inherit from their python value types, for good or
# ill. Python's builtin `bool` cannot be sub-classed and is itself a sub-class
# of int so we just sub-class int directly for our Ion Boolean.
# Considering that True == 1 and False == 0 this works as expected.
IonPyBool = _ion_type_for('IonPyBool', int, IonType.BOOL)

# We override __repr__ so Booleans show up as True|False and not 1|0.
# The representation is consistent with other primitives in that it returns a
# string repr of the value but not annotations.
IonPyBool.__repr__ = lambda self: str(bool(self))


class IonPySymbol(SymbolToken, _IonNature):
def __init__(self, *args, **kwargs):
Expand Down
4 changes: 3 additions & 1 deletion tests/test_equivalence.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,14 @@ def _ion_nature(_ion_nature_cls, ion_type, value=None, annotations=()):
)

_NONEQUIVS = (
# For each tuple, each element is not equivalent to any other element equivalent under the Ion data model.
# For each tuple, each element is not equivalent to any other element
# under the Ion data model.
(None, 0, _null(_IT.BOOL)),
(True, False),
(True, _bool(False)),
(_bool(True), False),
(_bool(True), _bool(False)),
(_bool(True), _int(1)), # True == 1 in python but not in the ion datamodel
(1, -1, 1.),
(1, _int(-1), _float(1)),
(_int(1), _int(-1)),
Expand Down

0 comments on commit 56cf39a

Please sign in to comment.