Python Forum
with statement odd feature
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
with statement odd feature
#5
(May-12-2020, 11:43 PM)Skaperen Wrote: i expected it to throw syntax errors in the compile phase. i guess it compiled the raise in place of them.

look at docs for Compound statements: the with statement

Quote:with_stmt ::= "with" with_item ("," with_item)* ":" suite
with_item ::= expression ["as" target]

....
5. If a target was included in the with statement, the return value from __enter__() is assigned to it.

providing target is optional and there is no SyntaxError. Your snippet raise NameError and then the except catch it.


Also in PEP343, Specification: The 'with' Statement:

Quote:
with EXPR as VAR:
    BLOCK
...

The "as VAR" part is optional.

...

If the "as VAR" part of the syntax is omitted, the "VAR =" part of the translation is omitted (but mgr.__enter__() is still called).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
with statement odd feature - by Skaperen - May-11-2020, 08:13 PM
RE: with statement odd feature - by ndc85430 - May-12-2020, 04:51 AM
RE: with statement odd feature - by buran - May-12-2020, 05:03 AM
RE: with statement odd feature - by Skaperen - May-12-2020, 11:43 PM
RE: with statement odd feature - by buran - May-13-2020, 04:19 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020