PEP new assert idiom

Alex Martelli aleaxit at yahoo.com
Sat Nov 6 17:35:05 EST 2004


Fábio Mendes <niels_bohr at uol.com.br> wrote:
   ...
> This elegant syntax is NOT equivalent to python's not so ellegant:
> 
> >>> erromsg = 'Errormsg'
> >>> assert statement 1, errormsg 
> >>> assert statement 2, 'errormsg
> >>> (...)
> >>> assert statement n, errormsg

Why isn't this equivalent?  Apart from the fact that you keep, here and
elsewhere, using 'statement' where you hopefully mean 'expression' --
you cannot assert a statement, you can only assert an expression.

> In Ruby, the Assertion error is raised if executing statement 1, then 2,
> then 3... etc raises an error. This is a subtle thingm the error COULD
> NOT be raised if each statement is executed alone, as each statement may
> have side effects which make the order of execution relevant. To

Can you give one Python example where the sequence of asserts would
behave differently from what you propose?  I cannot see any.

> suceccefully emulate this behaviour, the python programmer have to
> resort to a even more cumbersome solution:
> 
> >>> foo = lambda : (statement 1) and (statement 2) ... (statement n)
> >>> assert foo, 'Errormsg'

I assume you mean to call foo, because if you don't, it will surely be
true and the assert will just never trigger.

Now, calling expressions expressions, rather than very confusingly
statements, can you explain how the semantics of this, with foo being
called, would differ from those of

assert exp1 and exp2 and exp3 ... and expN, 'errormsg'

???


> My proposal is to add the following syntax to the language:
> 
> >>> assert (statement 1), (statement 2), ... (statement n), 'Errormsg'

Again: can you explain how the semantics of this, would differ from
those of:

assert exp1 and exp2 and exp3 ... and expN, 'errormsg'

???

> Or, if the user prefers, the traditional comma rules also applies:

There is no such "traditional" rule (or rules) in Python.  Both a
statement and an expression can perfectly well end in a comma; the comma
does NOT imply any kind of continuation.


Alex



More information about the Python-list mailing list