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.
People keep saying this, but iterable unpacking looks like assigning to a literal (a tuple or list literal) just as much.
Also PEP 622 proposes something that looks like assignment to a function call, albeit within a match/case statement.
It's natural to have symmetry between assignments and expression. For another example, look at subscripting, i.e. `__getitem__` vs `__setitem__`.
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's really not. A decent IDE should already be able to automatically show you assignments and usages of a variable - PyCharm does with one Ctrl+click. A syntax highlighter that can handle f-strings will make the assignments obvious at a glance.
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).
This I agree with, another reason to go for putting regexes in the f-strings like I suggested.
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'
I think someone else just made the same proposal. But how does this solve the greediness issue?
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.
How is
f"{a} {b}" = "1 2"
creating local variables any more "programmatically" than
a, b = "1 2".split()
? The variables are static and visible to the compiler.