{"record":{"id":"68c9c7544a89bc52","repo":"jax-ml/jax","slug":"key-array-cannot-be-converted-to-boolean","errorCode":null,"errorMessage":"key array cannot be converted to boolean.","messagePattern":"key array cannot be converted to boolean\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"jax/_src/random/prng.py","lineNumber":311,"sourceCode":"      raise TypeError('len() of unsized object')\n    return len(self._base_array)\n\n  def __iter__(self) -> Iterator[PRNGKeyArray]:\n    if self._is_scalar():\n      raise TypeError('iteration over a 0-d key array')\n    # TODO(frostig): we may want to avoid iteration by slicing because\n    # a very common use of iteration is `k1, k2 = split(key)`, and\n    # slicing/indexing may be trickier to track for linearity checking\n    # purposes. Maybe we can:\n    # * introduce an unpack primitive+traceable (also allow direct use)\n    # * unpack upfront into shape[0] many keyarray slices\n    # * return iter over these unpacked slices\n    # Whatever we do, we'll want to do it by overriding\n    # ShapedArray._iter when the element type is KeyTy...\n    return (PRNGKeyArray(self._impl, k) for k in iter(self._base_array))\n\n  def __bool__(self):\n    raise TypeError(\"key array cannot be converted to boolean.\")\n\n  def __repr__(self):\n    return (f'Array({self.shape}, dtype={self.dtype.name}) overlaying:\\n'\n            f'{self._base_array}')\n\n  def pprint(self):\n    pp_keys = pp.text('shape = ') + pp.text(str(self.shape))\n    pp_impl = pp.text('impl = ') + self._impl.pprint()\n    return str(pp.group(\n      pp.text('PRNGKeyArray:') +\n      pp.nest(2, pp.brk() + pp_keys + pp.brk() + pp_impl)))\n\n  def copy(self):\n    out = self.__class__(self._impl, self._base_array.copy())\n    out._consumed = self._consumed  # TODO(jakevdp): is this correct?\n    return out\n\n  __hash__ = None","sourceCodeStart":293,"sourceCodeEnd":329,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/random/prng.py#L293-L329","documentation":"PRNGKeyArray deliberately disables truthiness (__bool__ raises) because there is no meaningful boolean interpretation of a random key. Any use of a key in a boolean context — if key:, key or other, not key, assert key — triggers this TypeError. This is a design decision to prevent silently treating keys as truthy/falsy objects.","triggerScenarios":"if key: ...; bool(key); using a key as a condition in 'key or default' expressions; assert key in tests; filter/map predicates that receive keys.","commonSituations":"Optional-argument patterns like 'key = key or jax.random.key(0)' ; truthiness checks in generic validation helpers; notebook-style asserts on objects.","solutions":["Replace truthiness with an explicit None check: if key is None: key = jax.random.key(0)","Use isinstance(key, jax.Array) and jax.dtypes.issubdtype(key.dtype, jax.dtypes.prng_key) to validate","Never use keys directly in boolean expressions"],"exampleFix":"// before\nkey = key or jax.random.key(0)  # TypeError\n\n// after\nkey = key if key is not None else jax.random.key(0)","handlingStrategy":"type-guard","validationCode":"if key is None:\n    key = jax.random.key(0)","typeGuard":"import jax, jax.numpy as jnp\ndef is_typed_key(x) -> bool:\n    return isinstance(x, jax.Array) and jax.dtypes.issubdtype(x.dtype, jax.dtypes.prng_key)","tryCatchPattern":null,"preventionTips":["Never use truthiness on key arrays; check 'is None' explicitly","Validate keys with is_typed_key before use"],"tags":["jax","prng","truthiness","bool"],"backgroundTag":"jax-prng-key-validation","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}