bazelbuild / bazelbuild/bazel

Starlark: Disallow conversion of `select` to bool

Open
#14,506 5 comments 4 reactions 0 assignees View on GitHub
P2 team-Loading-API type: feature request
Dominant language
Java
Stars
25.8k
Forks
4.6k
Avg merge
2d 18h
Merged PRs (30d)
75

Description

### Description of the problem / feature request:

The return type of `select` converts silently in truthy contexts to `True`.
This can lead to the following code being legal, but not doing what the programmer intended to do:
```python
def is_linux():
return select({
"@platforms//os:linux": True,
"//conditions:default": False
})

def my_macro()
if is_linux():
# do one thing
else:
# do another thing
```

This can lead to behavior that bazel novices would think of as unexpected (the if always evaluates to the true branch).
Instead, bazel should emit a warning or an error whenever the return value of select gets converted to a bool.
I cannot imagine any valid use case where the return of a select should be converted to a truth value (it's always `True` anyways), so taking this behavior away, while a breaking change, would be an improvement for bazel.
### Feature requests: what underlying problem are you trying to solve with this feature?
Improve the user experience for a more confusing part of starlark (selects), by providing a clear error on a beginner mistake.

### Have you found anything relevant by searching the web?

The documentation [calls this starlark behavior out](https://docs.bazel.build/versions/main/configurable-attributes.html#why-does-select-always-return-true), but I believe that in this case, starlark should diverge from the pythonic way that everything silently converts to bool without fail.
The reasoning for that is mainly that understanding `select` and the bazel/starlark execution semantics is difficult enough as-is, and this change would remove a pitfall.

Contributor guide

Open the contributing guide

Research direction

Begin with the configurable-attributes documentation linked in the issue, then locate the Starlark implementation and tests governing select truth-value conversion. Done means the proposed warning or error is defined, implemented, and covered for conversions of select results to bool without breaking valid behavior.

Written by the indexing model from the issue text.

Assessment

Domain
build-system
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.