On Thu, 2 Jul 2020 at 00:04, Elliott Chen elliottchen2004@gmail.com wrote:
I saw in the PEP that "Allow more flexible assignment targets instead" was rejected, but I actually think it's a good idea. The current PEP means there will be two different, subtly incompatible ways to destructure objects (match statement and iterable unpacking). The reasoning given was that most cases involve an if-statement, but there's no reason we can't have both flexible assignment targets and a match statement. I think unifying the concepts will make the language more consistent and easy to learn.
I also think destructuring an object with only one possible pattern can be very useful, without the boilerplate to set up an entire match suite and manually raise an exception. This will make the variable assignment statement much more powerful. I don't see a good reason to arbitrarily restrict variable assignment to only allow sequence patterns. This might not be a good idea, but it can even potentially be used as an assert statement, like this:
def __init__(self, version, name, point): self.version = 1 | 2 | 3 = type # assert that "version" is between 1 and 3 self.name = str() = string # assert that "name" is the correct type Point(0, self.y) = point # assert that "point" is on the y-axis
The constant value pattern would have to be changed to something else, like "@constant", and even though that's also rejected, I think the benefits outweigh the costs here. The special treatment of "_" would have to go too, but there's no reason it can't be used as a wildcard by convention anyway, similar to how it can already be used in for loops. I don't see any benefit in treating it specially. Or the question mark can be the wildcard instead.
Exactly!
The wildcard spelling idea I suggested in the other thread was that "?" could become a general constraint prefix used to introduce non-literal and non-keyword constraints.
I was thinking purely in terms of destructuring and not in terms of data validation, but you're right that multiple assignments would allow for "multi-capture" (albeit with the usual caveats on iterable consumption).
(I think match/case is fine as the spelling for the multi-target dispatch case, though)
Cheers, Nick.