Skip to content

[Python] bool(pa.scalar(False)) evaluates to True #34987

Open

Description

@randolf-scholz

Describe the bug, including details regarding any error messages, version, and platform.

This can easily cause bugs: assert pa.scalar(False) will not raise AssertionError!

Component(s)

Python

Activity

  1. zfoobar commented on Apr 8, 2023

    @zfoobar

    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.

  2. randolf-scholz commented on Apr 8, 2023

    @randolf-scholz
    Author

    @zfoobar pyarrow.BooleanScalar needs to implement the __bool__ magic method and return the appropriate python boolean. For example, here is how numpy does it:

    b = np.bool_(False)
    print(type(b))  # <class 'numpy.bool_'>
    c = bool(b)
    print(type(c))  # <class 'bool'>
  3. randolf-scholz commented on Apr 8, 2023

    @randolf-scholz
    Author

    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.

  4. zfoobar commented on Apr 9, 2023

    @zfoobar

    Makes total sense.

  5. added a commit that references this issue on Apr 9, 2023
  6. randolf-scholz commented on Apr 9, 2023

    @randolf-scholz
    Author

    I think it is worth discussing what to do in case when the boolean is null. There are 4 options:

    1. Raise an Exception. For example, pandas raises a TypeError
    import pandas as pd
    bool(pd.NA)  # TypeError: boolean value of NA is ambiguous
    1. Return None, which would evaluate to False in boolean context.
    2. Coerce missing values to False
    3. 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.

  7. zfoobar commented on Apr 9, 2023

    @zfoobar

    @randolf-scholz PR updated with your wonderful insights. any additional thoughts upon review?

  8. randolf-scholz commented on Apr 10, 2023

    @randolf-scholz
    Author

    @zfoobar LGTM. Possibly pylint will complain about is the unnecessary else, but that's nitpicking.

  9. changed the title [-]`bool(pa.scalar(False))` evaluates to `True`[/-] [+][Python] `bool(pa.scalar(False))` evaluates to True[/+] on Apr 10, 2023
  10. jorisvandenbossche commented on Apr 10, 2023

    @jorisvandenbossche
    Member

    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)

  11. randolf-scholz commented on Apr 10, 2023

    @randolf-scholz
    Author

    @jorisvandenbossche

    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:

    assert pa.compute.all(pa.compute.invert(array.is_null()))

    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.

  12. zfoobar commented on Apr 10, 2023

    @zfoobar

    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...

  13. danepitkin commented on Apr 18, 2023

    @danepitkin
    Member

    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.

  14. danepitkin commented on Apr 20, 2023

    @danepitkin
    Member

    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.)

  15. AlenkaF commented on Nov 19, 2025

    @AlenkaF
    Member

    There has been changes in the meantime where __bool__ method has been added to the BooleanScalar class, see: https://github.com/apache/arrow/pull/45818/files#diff-0d5c7373af0f1e13f3feacf7a4fdb4e99f979e162379160ae1cd8efeb726add5

    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.

  16. randolf-scholz commented on Nov 19, 2025

    @randolf-scholz
    Author

    @AlenkaF Thanks for the heads-up!

    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:

    import pyarrow as pa
    measured_value = pa.scalar(None, type=pa.float64())  # missing value
    limit_value = pa.scalar(1.0, type=pa.float64())
    exceeds_limit = pa.compute.greater(measured_value, limit_value)
    
    # user forgot to handle the missing value case
    if exceeds_limit:  
        raise ValueError("Measured value exceeds safe limit")
    else:  # <- we incorrectly assume safe branch when sensor is malfunctioning.
         # continue system operation as usual
         pass

    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.

  17. AlenkaF commented on Dec 3, 2025

    @AlenkaF
    Member

    @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.

  18. pitrou commented on Dec 3, 2025

    @pitrou
    Member

    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:

    >>> bool(pa.scalar(None, type=pa.bool_()))
    False
    >>> bool(pa.scalar(None, type=pa.int8()))
    True
    >>> bool(pa.scalar(None))
    True

    I also think non-null scalars should have similar boolean evaluation as the corresponding Python values:

    >>> bool(0)
    False
    >>> bool(pa.scalar(0))
    True

    NumPy does this too:

    >>> bool(np.int8(0))
    False
    >>> bool(np.float16(0))
    False
  19. randolf-scholz commented on Dec 3, 2025

    @randolf-scholz
    Author

    I think bool should return False if the given scalar is null.

    @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 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:

    1. gains very little
    2. has the potential for very nasty bugs if one forget to check for Null
  20. pitrou commented on Dec 3, 2025

    @pitrou
    Member

    @pitrou Do you not think my comment #34987 (comment) and #34993 (comment) here make a good case why this behavior may be undesirable?

    No, I don't :)

    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.

    It is unavoidable that casting to bool loses some information, so you are assumed to have thought of the various cases.

    Disallowing bool(pa.scalar(None)) while bool(None) is allowed would not be very user-friendly.

    My worry is that by allowing Null to be cast to False, one:

    1. gains very little
    2. has the potential for very nasty bugs if one forget to check for Null

    The same can be said of casting Null to True, though, so that doesn't sound like a good argument.

    @jorisvandenbossche What do you think about this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions