by bluecalm · 8y ago · 0 comments
With PEP 572 it wasn't like that. There wasn't a Pythonic way to do list comprehensions which used the same expensive to evaluate expression two times in it and it was I think the only glaring syntax weakness in comparison to languages which have a way to do that (like WHERE keyword in Haskell).
</Sarcasm>
But seriously, I think there's no one way to do things anymore especially if it holds up productivity and effectiveness. Let the pattern matching begin.
[foo(y, y) for x in xs for y in [f(x)]]
Is this Pythonic? Perhaps not, but mainly because multiline list comprehensions are frowned on in general. I think people tend to get too dogmatic about that.Python does that with tuples:
a, b = b, a
But it just stops there. To be fair, I don't know how much power it would gain by going further either. Never made that question.Pattern matching is normally (in functional languages like Scala and Haskell anyway) defined as a way of taking a union type and handling each one safely. It's a sort of functional alternative to polymorphism.
That is, polymorphic code
class Dog(Animal):
def make_noise(self):
return "bork bork"
class Duck(Animal):
def make_noise(self):
return "quack"
would, with pattern matching be (in pseudo haskell I hope) make_noise :: Animal -> str
make_noise Duck = "quack"
make_noise Dog = "bork bork"
In other words, in an oop style you delegate to the object that it implements all methods. Whereas with pattern matching you can have a type delegate to each of the functions that can operate on it to handle it correctly. (This explanation is a disservice to functional styles, its a lot more elegant than what I describe if you do it correctly).It's why it's hard.