You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Python] bool(pa.scalar(False)) evaluates to True #34987
False is a valid value for a Boolean Scalar in this context, so it won't return 0, it will return an object specialized as boolean.
I guess the question would be: what wouldn't be acceptable to pyarrow as a scalar? Most of the types return scalar objects - including list, tuple, strings, etc.
@zfoobarpyarrow.BooleanScalar needs to implement the __bool__ magic method and return the appropriate python boolean. For example, here is how numpy does it:
I guess the question would be: what wouldn't be acceptable to pyarrow as a scalar? Most of the types return scalar objects - including list, tuple, strings, etc.
It's not about what is acceptable as a scalar. It's about which scalars should be considered Truthy and Falsey. In python the convention is:
Boolean/Integer/Float/Complex: 0 → False, other →True
Container-Types (string/list/tuple): same as bool(len(obj))
For other types (dates, timestamps, etc.) I'm not sure a boolean conversion makes sense.
I think it is worth discussing what to do in case when the boolean is null. There are 4 options:
Raise an Exception. For example, pandas raises a TypeError
importpandasaspdbool(pd.NA) # TypeError: boolean value of NA is ambiguous
Return None, which would evaluate to False in boolean context.
Coerce missing values to False
Coerce missing values to True
Options 3 and 4 do not make sense imo. Option 2 would have been my presonally preferred one if python was using None as part of a 3-valued logic. But it doesn't, so I think option 1 is currently the best bet.
In cases where the user does not want this exception, the as_py method could be given an additional keyword argument that handles the treatment of null.
While I certainly agree the current behaviour is not ideal, I am a bit hesitant to just add __bool__ to the boolean scalars.
Several broader questions for __bool__ itself:
If we add it to BooleanScalar, we should probably add it to all other scalars as well?
If we add it to other scalar types, what should be its behaviour? For other numeric types it probably makes sense to follow 0 being falsey. But personally I am not fully convinced we should start making ListScalars truthy/falsey depending on the length of the list scalar value.
As @randolf-scholz already mentioned, we then also need to make a decision about the truthy value of null.
But aside from bool(..) there are other aspects that people would then expect from normal "scalar" values, such as equality. Currently __eq__ is very dumb, so doing pa.scalar(None) == pa.scalar(None) gives True (while that doesn't match element-wise equality behavior for the array with equivalent values) or it requires exact types (again not being consistent with the element-wise "equal" kernel)
We could also say: if you want python-like scalar behaviour, just call as_py() on the pyarrow scalar.
(and we could also raise an error in __bool__ always, to make it clear this method isn't actually implemented)
We could also say: if you want python-like scalar behaviour, just call as_py() on the pyarrow scalar.
(and we could also raise an error in bool always, to make it clear this method isn't actually implemented)
Certainly that could be better than the current situation. I opened this issue after the following code silently failed:
Currently __eq__ is very dumb, so doing pa.scalar(None) == pa.scalar(None) gives True (while that doesn't match element-wise equality behavior for the array with equivalent values) or it requires exact types (again not being consistent with the element-wise "equal" kernel)
That just seems really bad behavior as well. pa.compute.equal(pa.scalar(None, type=pa.bool_()), pa.scalar(None, type=pa.bool_())) returns <pyarrow.BooleanScalar: None>, so pa.scalar(None, type=pa.bool_()) == pa.scalar(None, type=pa.bool_() should return this as well. This should be fine, since if the result of this equality will be used in context where a python boolean is expected the casting to bool will raise the TypeError, if we follow option 1 from my other comment.
Just coming at this from the lens of a newb user - not even considering the Null case:
>>> a = pa.scalar(1)
>>> b = pa.scalar(2)
>>> assert(pc.equal(a,b))
>>>
^^ It wouldn't immediately occur to me to even know what as_py() is or to use it to ensure the expected behavior in this case. A solid RTFM could be in order but to my eye it wasn't immediately clear that this should be done.
Agree that __eq__ returning boolean object, which can then be relied on to provide __bool__ seems correct.
To @jorisvandenbossche's point, I did feel odd only adding __bool__ implementation for a single data type. =/
Happy to take another swing at this if we can align on an implementation, otherwise as_py() it is...
I'll add a +1 for implementing the intuitive usage of __bool__ and __eq__ across scalar types (maybe split into 2 PRs). I don't think requiring usage of as_py() is as user-friendly in the long term.
After further thought, its probably best to just update for the bool scalar now and save the rest of this discussion/implementation for a larger refactor (e.g. how should each scalar handle bool, eq, lt, gt, etc.)
This issue slipped past and so the current code decides boolean value of None is False and it only implements the method for BooleanScalar, not other scalars.
I am happy to correct the current situation to better reflect this discussion.
This issue slipped past and so the current code decides boolean value of None is False and it only implements the method for BooleanScalar, not other scalars.
Well, as I explained in #34993 (comment) this could have some unexpected consequences, and it may be safer to actually error on casting null to bool. For example:
importpyarrowaspameasured_value=pa.scalar(None, type=pa.float64()) # missing valuelimit_value=pa.scalar(1.0, type=pa.float64())
exceeds_limit=pa.compute.greater(measured_value, limit_value)
# user forgot to handle the missing value caseifexceeds_limit:
raiseValueError("Measured value exceeds safe limit")
else: # <- we incorrectly assume safe branch when sensor is malfunctioning.# continue system operation as usualpass
While it is true that python treats None as False in a boolean context, python forbids arithmetic with None, e.g. None > 1.0 raises a type error rather than returning None.
@pitrou what do you think? We have introduced __bool__ implementation in 21.0.0 which mimics Python behaviour bool(None) == False. But this discussion is of a different opinion where for pyarrow Scalar we would want bool(pa.scalar(None, pa.bool_())) to raise ValueError.
If we agree this should be changed we would need to deprecate the current behaviour (after 2 releases 😁) and we might do this together with changing the behaviour of __eq__, see #32007.
I think __bool__ should return False if the given scalar is null. It's already the case for boolean scalars but it should be the case for other scalars as well:
In python None and bool are different types. While it is true that None can be cast to a boolean, giving False, None typically doesn't fall out of other arithmetic because python's builtin types are not nullable.
So when one does something like if value > reference with builtin types, like float, there is no possibility to accidentally coerce a None to False.
However, with arrow, all scalars are nullable, and the usual interpretation is that Null ⇿ missing value. So if I were to do if value > reference: with pyarrow types, there are actually 3 options: True, False or Null, i.e. we have a 3-valued logic.
In my estimation, one would usually want to handle the Null case separately, same as in python, even the comparison value > reference would be illegal if value were float | None instead of just float.
My worry is that by allowing Null to be cast to False, one:
gains very little
has the potential for very nasty bugs if one forget to check for Null
Activity
zfoobar commentedon Apr 8, 2023
False is a valid value for a Boolean Scalar in this context, so it won't return 0, it will return an object specialized as boolean.
I guess the question would be: what wouldn't be acceptable to pyarrow as a scalar? Most of the types return scalar objects - including list, tuple, strings, etc.
randolf-scholz commentedon Apr 8, 2023
@zfoobar
pyarrow.BooleanScalarneeds to implement the__bool__magic method and return the appropriate python boolean. For example, here is hownumpydoes it:randolf-scholz commentedon Apr 8, 2023
It's not about what is acceptable as a scalar. It's about which scalars should be considered Truthy and Falsey. In python the convention is:
bool(len(obj))For other types (dates, timestamps, etc.) I'm not sure a boolean conversion makes sense.
zfoobar commentedon Apr 9, 2023
Makes total sense.
See issue: apache#34987 - user requests Truthy/Falsey for boolean sca…
randolf-scholz commentedon Apr 9, 2023
I think it is worth discussing what to do in case when the boolean is null. There are 4 options:
TypeErrorNone, which would evaluate toFalsein boolean context.FalseTrueOptions 3 and 4 do not make sense imo. Option 2 would have been my presonally preferred one if python was using
Noneas part of a 3-valued logic. But it doesn't, so I think option 1 is currently the best bet.In cases where the user does not want this exception, the
as_pymethod could be given an additional keyword argument that handles the treatment ofnull.zfoobar commentedon Apr 9, 2023
@randolf-scholz PR updated with your wonderful insights. any additional thoughts upon review?
randolf-scholz commentedon Apr 10, 2023
@zfoobar LGTM. Possibly
pylintwill complain about is the unnecessary else, but that's nitpicking.[-]`bool(pa.scalar(False))` evaluates to `True`[/-][+][Python] `bool(pa.scalar(False))` evaluates to True[/+]jorisvandenbossche commentedon Apr 10, 2023
While I certainly agree the current behaviour is not ideal, I am a bit hesitant to just add
__bool__to the boolean scalars.__bool__itself:bool(..)there are other aspects that people would then expect from normal "scalar" values, such as equality. Currently__eq__is very dumb, so doingpa.scalar(None) == pa.scalar(None)gives True (while that doesn't match element-wise equality behavior for the array with equivalent values) or it requires exact types (again not being consistent with the element-wise "equal" kernel)We could also say: if you want python-like scalar behaviour, just call
as_py()on the pyarrow scalar.(and we could also raise an error in
__bool__always, to make it clear this method isn't actually implemented)randolf-scholz commentedon Apr 10, 2023
@jorisvandenbossche
Certainly that could be better than the current situation. I opened this issue after the following code silently failed:
That just seems really bad behavior as well.
pa.compute.equal(pa.scalar(None, type=pa.bool_()), pa.scalar(None, type=pa.bool_()))returns<pyarrow.BooleanScalar: None>, sopa.scalar(None, type=pa.bool_()) == pa.scalar(None, type=pa.bool_()should return this as well. This should be fine, since if the result of this equality will be used in context where a python boolean is expected the casting to bool will raise the TypeError, if we follow option 1 from my other comment.zfoobar commentedon Apr 10, 2023
Just coming at this from the lens of a newb user - not even considering the Null case:
^^ It wouldn't immediately occur to me to even know what as_py() is or to use it to ensure the expected behavior in this case. A solid RTFM could be in order but to my eye it wasn't immediately clear that this should be done.
Agree that
__eq__returning boolean object, which can then be relied on to provide__bool__seems correct.To @jorisvandenbossche's point, I did feel odd only adding
__bool__implementation for a single data type. =/Happy to take another swing at this if we can align on an implementation, otherwise as_py() it is...
danepitkin commentedon Apr 18, 2023
I'll add a +1 for implementing the intuitive usage of
__bool__and__eq__across scalar types (maybe split into 2 PRs). I don't think requiring usage ofas_py()is as user-friendly in the long term.danepitkin commentedon Apr 20, 2023
After further thought, its probably best to just update for the
boolscalar now and save the rest of this discussion/implementation for a larger refactor (e.g. how should each scalar handle bool, eq, lt, gt, etc.)AlenkaF commentedon Nov 19, 2025
There has been changes in the meantime where
__bool__method has been added to theBooleanScalarclass, see: https://github.com/apache/arrow/pull/45818/files#diff-0d5c7373af0f1e13f3feacf7a4fdb4e99f979e162379160ae1cd8efeb726add5This issue slipped past and so the current code decides boolean value of
NoneisFalseand it only implements the method forBooleanScalar, not other scalars.I am happy to correct the current situation to better reflect this discussion.
randolf-scholz commentedon Nov 19, 2025
@AlenkaF Thanks for the heads-up!
Well, as I explained in #34993 (comment) this could have some unexpected consequences, and it may be safer to actually error on casting
nulltobool. For example:While it is true that python treats
NoneasFalsein a boolean context, python forbids arithmetic withNone, e.g.None > 1.0raises a type error rather than returningNone.AlenkaF commentedon Dec 3, 2025
@pitrou what do you think? We have introduced
__bool__implementation in 21.0.0 which mimics Python behaviourbool(None) == False. But this discussion is of a different opinion where for pyarrow Scalar we would wantbool(pa.scalar(None, pa.bool_()))to raiseValueError.If we agree this should be changed we would need to deprecate the current behaviour (after 2 releases 😁) and we might do this together with changing the behaviour of
__eq__, see #32007.pitrou commentedon Dec 3, 2025
I think
__bool__should return False if the given scalar is null. It's already the case for boolean scalars but it should be the case for other scalars as well:I also think non-null scalars should have similar boolean evaluation as the corresponding Python values:
NumPy does this too:
randolf-scholz commentedon Dec 3, 2025
@pitrou Do you not think my comment #34987 (comment) and #34993 (comment) here make a good case why this behavior may be undesirable?
In essence, it kind of boils down to this:
In python
Noneandboolare different types. While it is true thatNonecan be cast to a boolean, givingFalse,Nonetypically doesn't fall out of other arithmetic because python's builtin types are not nullable.So when one does something like
if value > referencewith builtin types, likefloat, there is no possibility to accidentally coerce aNonetoFalse.However, with
arrow, all scalars are nullable, and the usual interpretation is thatNull⇿ missing value. So if I were to doif value > reference:with pyarrow types, there are actually 3 options:True,FalseorNull, i.e. we have a 3-valued logic.In my estimation, one would usually want to handle the
Nullcase separately, same as in python, even the comparisonvalue > referencewould be illegal ifvaluewerefloat | Noneinstead of justfloat.My worry is that by allowing
Nullto be cast toFalse, one:Nullpitrou commentedon Dec 3, 2025
No, I don't :)
It is unavoidable that casting to
boolloses some information, so you are assumed to have thought of the various cases.Disallowing
bool(pa.scalar(None))whilebool(None)is allowed would not be very user-friendly.The same can be said of casting
Nullto True, though, so that doesn't sound like a good argument.@jorisvandenbossche What do you think about this?