google / starlark-go

Starlark in Go: the Starlark configuration language, implemented in Go
BSD 3-Clause "New" or "Revised" License
2.31k stars 209 forks source link

Add support for Identity comparisons `is` and `is not` #526

Closed RussellLuo closed 7 months ago

RussellLuo commented 7 months ago

First of all, thanks for the awesome project!

Sometimes, we need to check if a variable is None. Python has support for Identity comparisons, which are not supported by Starlark:

x is None # yields error ":1:5: got illegal token after expression, want EOF"
0 if x is None else 1 # yields error ":1:3: conditional expression without else clause"

For the above example, the workaround is to use == instead of is, which works but is not Pythonic:

x == None # yields False for non-None x
0 if x == None else 1 # yields 1 for non-None x

Is there any plan to add support for operators is and is not in Starlark?

adonovan commented 7 months ago

There are no plans, and for the specific case of x is None, the expression x == None is equivalent and no less efficient. That said, I think it is completely reasonable in a language with mutation to expect an operator that answers the question of whether two variables are identical.

I suggest you file a proposal to change the language spec at https://github.com/bazelbuild/starlark.

adonovan commented 7 months ago

In the meantime, I'm going to close this issue. If there is consensus for a spec change, we can reopen it.

RussellLuo commented 7 months ago

Thanks for the reply!

Unfortunately, I found that Starlark explicitly states that No is operator:

The is operator adds a new concept (identity test) that we did not really need. In Python, the is operator is implementation-dependent, it can have a surprising behavior, and be a source of bugs. Supporting only the equality operator simplified the language.

adonovan commented 7 months ago

Thanks for the reply!

Unfortunately, I found that Starlark explicitly states that No is operator:

The is operator adds a new concept (identity test) that we did not really need. In Python, the is operator is implementation-dependent, it can have a surprising behavior, and be a source of bugs. Supporting only the equality operator simplified the language.

Yes, that was always the claim. The point about integers is valid, and I agree that the need for identity tests is not something that comes up very often in typical build configurations (say). But in any language with variables, one does on occasion need a way to ask whether two variables are the same; it's one of the most fundamental operations. So I still believe it should be added for completeness.