bazelbuild / starlark

Starlark Language
Apache License 2.0
2.38k stars 158 forks source link

Add an "assert" function #252

Open carlosgalvezp opened 1 year ago

carlosgalvezp commented 1 year ago

Hi,

There is already a fail function, but it's not ergonomic to use, because it takes 2 lines and 1 added indentation level. It would be good if we could have a assert function. Consider:

if (not condition):
   fail("Error message")

vs

assert(condition, "Error message")

The same code with assert is much cleaner. It's also consistent with most programming languages.

laurentlb commented 1 year ago

In Python 3, this line is a no op:

>>> assert(False, "abc")
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?

The syntax is actually without parentheses:

assert someExpression
assert someExpression, "error message"

So the request would require a change in the syntax (and all Starlark-aware tooling).

We would also need a way to prevent users from writing the no-op line assert(False, "abc"), as it's very error-prone.

fenollp commented 1 year ago

As someone that ported pytruth to Starlark (see https://github.com/google/starlark-go/pull/361) I'd like the assert statement to be correctly parsed so that I'd be able to bind its behavior in this way:

assert that("this").is_not_equal_to("that")

Today I'm able to declare assert as a module and that as its only method. I very awkwardly s/assert that/assert.that/g for the syntax support... so I support its addition to the spec!

carlosgalvezp commented 1 year ago

So the request would require a change in the syntax (and all Starlark-aware tooling).

I don't quite know the requirements of Starlark - is it a requirement that it must be Python3 - compatible? Creating an assert() function would be trivial if we didn't need to support the same Python3 syntax.