WTFPython – Understanding Python through surprising snippets
My biggest complaint about Python is that it somehow doesn’t get flak for having the same (if not worse) scoping as JS, which gets endless hate for its function-scoped variables. (So much so that block scoped variables are the new normal in JS, but not in Py!)Take for instance:>>> powers_of_x = [lambda x: x^i for i in range(10)]>>> [f(2) for f in powers_of_x][512, 512, 512, 512, 512, 512, 512, 512, 512, 512]To me this is more absurd than any of the JS “wat”s I’ve seen.In JS:powersOfX = Array.from({length: 10}).map((_,i) => x => x^i)powersOfX.map(f => f(2))Not a particular fan of the Array.from over list comprehensions in terms of syntax, but I much prefer consistency of semantics JS provides by not adding new syntax.Here Python has special syntax for both list comprehensions and for anonymous single line functions, and they interact in a highly unexpected way.Funny that Py doesn’t need semicolons, as I’m reminded of GJS telling me of adding special forms to languages: “beware the allure of syntactic sugar, lest you bring upon yourself the curse of the semicolon” (paraphrased of course, he said it much better). It seems Python has fallen into the trap of syntactic sugar, with the curse manifesting itself not in the form of a semicolon, but in confusing and unexpected interactions between its various special forms. Another example: the walrus operator and all its oddities listed in TFA.