[Python-Dev] PEP 572 and assert
On Tue, Jul 17, 2018 at 07:24:12PM +0300, Serhiy Storchaka wrote:
> 17.07.18 18:48, Guido van Rossum ????:
> >On Tue, Jul 17, 2018 at 8:28 AM, Serhiy Storchaka <storchaka at gmail.com
> ><mailto:storchaka at gmail.com>> wrote:
> > Should not the assert statement introduce an implicit lexical scope
> > for preventing leaking variables?
> >I don't see why. As Chris said, side effects in asserts are nothing new
> >and this PEP is not the one to do something about it.
> This side effect is new. No other expressions that can be used in
> asserts leaked local variables before.
assert vars().__setitem__('foo', 42) or foo
Not that anyone would write such a thing (and it probably won't work
inside a function in CPython), but it is possible.
Besides, there is a legitimate use for assignment expressions in
assert (spam := something) > 2, 'not enough spam'
assert sequence[foo] == 999, 'sequence item isn't 999'
Sometimes you need two assertions.
> We can't make the assignment expression itself creating its own scope,
> because this will invalidate its purpose. But the problem with assert
> ccould be solved by making assert creating a new lexical scope.
Assertions could be used to perform imports too:
but people don't do that either. Let's not try fixing "problems" that
won't exist. Most people have more sense than to do that.
And for those who don't and misuse assertions, well, they've been
misusing them for two decades and the sky hasn't fallen.
> assert expr, msg
> could be translated to
> if __debug__ and not (lambda: expr)():
> raise AssertionError(msg)
I do a lot of work in the REPL where I'm not afraid to bend the rules
and use hacks I'd never use in long-lasting code. I'd never use assert
for testing input in real code, but I do it in the REPL all the time.
If I choose to abuse assertions in the REPL, you ought to trust me to do
this responsibly. I'm a consenting adult. If I want to run with
scissors, point a loaded gun at my foot, put all my eggs in one basket,
or use assignment expressions in an assertion, I don't want the
interpreter telling me I can't.