Skip to content

ArrayBuilder.__bool__ raises TypeError when builder length is 1 #3732

@T90REAL

Description

@T90REAL

Version of Awkward Array

2.8.10

Description and code to reproduce

Calling bool() on an ak.ArrayBuilder should mirror the truthiness of its accumulated content when the builder holds exactly one element. The current implementation explicitly checks len(self) == 1, but then attempts to access self[0], even though ArrayBuilder does not implement __getitem__.

import awkward as ak

builder = ak.ArrayBuilder()
builder.boolean(False)  # could be any single value
print(len(builder))
print(bool(builder))
1
Traceback (most recent call last):
  File "/data/PBT-AgentSys-remote/src/test.py", line 6, in <module>
    print(bool(builder))     # triggers TypeError
          ^^^^^^^^^^^^^
  File "/home/hdd/miniconda3/envs/py312/lib/python3.12/site-packages/awkward/highlevel.py", line 2924, in __bool__
    return bool(self[0])
                ~~~~^^^
TypeError: 'ArrayBuilder' object is not subscriptable

bool(builder) should return the truthiness of the single accumulated element (False in the example).

A easy fix is probably gonna be:

diff --git a/src/awkward/highlevel.py b/src/awkward/highlevel.py
index e6f3f21..c0a1a02 100644
--- a/src/awkward/highlevel.py
+++ b/src/awkward/highlevel.py
@@
     def __bool__(self):
         if len(self) == 1:
-            return bool(self[0])
+            # ArrayBuilder is not subscriptable; fetch the value from the snapshot instead.
+            return bool(self.snapshot()[0])
         else:
             raise ValueError(
                 "the truth value of an array whose length is not 1 is ambiguous; "
                 "use ak.any() or ak.all()"
             )

Note: This issue was identified by an automated testing tool for academic research and manually verified. If you have any concerns about this type of reporting, please let me know, and I will adjust my workflow accordingly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThe problem described is something that must be fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions