On 2020-09-16 21:52, Dennis Sweeney wrote:
TL;DR: I propose the following behavior:

     >>> s = "She turned me into a newt."
     >>> f"She turned me into a {animal}." = s
     >>> animal
     'newt'

     >>> f"A {animal}?" = s
     Traceback (most recent call last):
     File "<pyshell#2>", line 1, in <module>
             f"A {animal}?" = s
     ValueError: f-string assignment target does not match 'She turned me into 
a newt.'

     >>> f"{hh:d}:{mm:d}:{ss:d}" = "11:59:59"
     >>> hh, mm, ss
     (11, 59, 59)

I don't like this at all. It looks like assigning to a literal, which is weird. Also, it hides the assignment target within a string of potentially unbounded length and complexity, which makes it difficult to reason about code because it's hard to see when variables are being assigned to. It also introduces a whole host of questions about the details of the parsing (i.e., how does the greediness work if the pattern is something like "{one} {two} {three} {four}" and the string to be parsed is five or ten words).

I think a better approach for something like this would be a .parse() method of some sort on strings, sort of like the inverse of .format(). It would parse a given string according to the format string and return a dict with the mappings (just as format can take a dict in and return the string with the substitutions made). So it would be like:

>>> pattern = "That {animal} is really {attribute}."
>>> d = pattern.parse("That snake is really powerful.")
>>> d['animal']
'snake'
>>> d['attribute']
'powerful'

This wouldn't let you assign the results into local variables, but I think that's a good thing. Creating local variables "programmatically" is not a good idea; it's better to use a dict.

--
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail."
   --author unknown
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VSNDVX4QXKUFY3R7KIAAYZK3PTH7PMQO/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to