On 12/01/24 10:33, Left Right via Python-list wrote:
By the way, in an attempt to golf this problem, I discovered this,
which seems like a parser problem:

This is what Python tells me about its grammar:

with_stmt:
     | 'with' '(' ','.with_item+ ','? ')' ':' block
     | 'with' ','.with_item+ ':' [TYPE_COMMENT] block
     | ASYNC 'with' '(' ','.with_item+ ','? ')' ':' block
     | ASYNC 'with' ','.with_item+ ':' [TYPE_COMMENT] block

with_item:
     | expression 'as' star_target &(',' | ')' | ':')
     | expression

 From which I figured why not something like this:

with (open('example.txt', 'r'), open('emails.txt', 'w'),
open('salutations.txt', 'w')) as e, m, s:
     for line in e:
         if line.strip():
             (m if '@' in line else s).write(line)

Which, surprise, parsers! But it seems like it's parse is wrong,
because running this I get:

❯ python ./split_emails.py
Traceback (most recent call last):
   File "/home/?/doodles/python/./split_emails.py", line 1, in <module>
     with (open('example.txt', 'r'), open('emails.txt', 'w'),
open('salutations.txt', 'w')) as e, m, s:
TypeError: 'tuple' object does not support the context manager protocol

It seems to me it shouldn't have been parsed as a tuple. The
parenthesis should've been interpreted just as a decoration.

NB. I'm using 3.11.6.
A series of comma-separated items will be parsed as a tuple (some people think it is bounding-parentheses which define).

In this case, the issue is 'connecting' the context-manager "expression" with its (as) "target". These should be more-closely paired:-

with ( open( 'example.txt', 'r', ) as e,
       open( 'emails.txt', 'w', ) as m,
       open( 'salutations.txt', 'w', ) as s
       ):

(NB code not executed here)


A data-architecture of having related-data in separated serial-files is NOT recommendable!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to