17 ms·
Show HN: Making Python one-liner-fit with the new pwk (Python With Kurly braces)
- andybak 6y ago> Python With Kurly braces I wasn't aware of this. I guess it might silence a few critics. However I'd be much more interested to try "Javascript with semantic white space"
- bobbylarrybobby 6y agoHow would JS with semantic whitespace difference from just auto-indenting a JS file?
- andybak 6y agoIt would look nicer.
- OJFord 6y agoSemantic whitespace looks nicer than non-semantic whitespace?
- andybak 6y agoNo curly braces looks nicer than curly braces.
- pindab0ter 6y agoAnd that’s just a fact.
- strombofulous 6y agoLamdas and first-class functions might make it pretty ugly, I definitely write `func(arg1, arg2, (res) => console.log(res))` from time to time
- bpicolo 6y agoWe tried that for a while, yeah? https://coffeescript.org/ https://coffeescript.org/
- andybak 6y agoOh god. You're right. I'd blotted that out of my memory.
- hobby-coder-guy 6y agoWhy?
- mbirth 6y agoAnd I loved it. So much more convenient than standard JavaScript.
- mistersys 6y agoCoffeeScript code bases are the scariest code bases on the planet, the nightmares. To me CoffeeScript inherited all the inconsistencies of JavaScript, then made the syntax inconsistent as well. It least it had optional chaining.
- irjustin 6y agoIt's weird right? I come from Rails and thought CoffeeScript (CS) could make it way more readable, like Python but with cool string interpolations! But you're absolutely right, it made my code really hard to reason about. I don't know why this is the case but it was always harder to read my own CS than raw JS. I found myself putting blocks into the CS2JS just to read inner workings. While it made me less verbose and short-term faster, longer term it made me slower.
- pkage 6y agoJavaScript has optional chaining now! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- cleandreams 6y agoThis meaningful whitespace thing in python is dreck. Hate it. I am not a python hater; this is from experience on projects (though this is now less of a problem because of IDE help). I like python and I choose it for my personal projects. I will probably use this.
- deleted 6y ago[deleted]
- alsko 6y ago> Just download and chmod it No source? No thanks. Edit: Discard this comment! I thought pwk in the repo was an executable because it did not have a ".py" ending and did not care to check. Sorry!
- OJFord 6y agoWhat? It's a python script, 'it' there is the source. It's executable via the python interpreter given in its shebang line.
- neycmrtn 6y ago"pwk" is both code and "executable" -- you can open it with any text editor. I didn't want to name it "pwk.py" to save on typing on the command line. --m
- pvg 6y agoYou don't need to sign your messages on HN (not really obvious since it's not written anywhere but it's one of those HN things)
- alsko 6y agoWow, I feel _really_ dumb now - I just saw the filename without ".py" and assumed it was an executable Sorry, I take it back!
- OJFord 6y agoIt's sort of just pedantry because I know what you mean, but FYI it is an executable when you mark it (chmod +x) as such; what you mean to say is that you assumed it was a binary, the output of a compiler, with the input (source) not provided.
- OJFord 6y agoNot even a nod to __future__.braces?
- adzm 6y agoNot a chance
- neycmrtn 6y agoThx, didn't know that one! Added ref to github (and thx to you)! --Martin
- deleted 6y ago[deleted]
- felixhummel 6y agoFor the uninitiated: $ python -c 'from __future__ import braces' File "<string>", line 1 SyntaxError: not a chance
- corytheboyd 6y agoCan someone help me understand the rationale behind semantic whitespace as a replacement for explicit delimiters? Is it purely aesthetic?
- codetrotter 6y agoIt forces consistent formatting within a file. But I think it was more relevant years ago. These days I see a lot of people using code formatters.
- corytheboyd 6y agoYeah that makes a bit more sense, thinking back to arguments about aligning hash key/value pairs in code reviews and how that just never seems to come up anymore (thank god)
- mtalantikite 6y agoI still think one of Go’s best contributions was formatting with ‘go fmt’. It’s refreshing to see so many language communities just embrace a format on save standard and keep it moving. Reading Python has always been a bit of a headache for me, but that probably has as much to do with the lack of type annotations as it does the lack of braces.
- georgyo 6y agoAuto formatters are the future, why should humans ever have to manually format or discuss how it should look ever again. However, languages that have a line length limit are the blight of them. There isn't a python formatter that won't make everything mush. My if clause that is 81 chars wide doesn't need to be broken up. Similar, my strings don't need to be reflowed. Go fmt ignores line length, and always produces a formatted file that is pretty as a result.
- rjmorris 6y agoYou can change the max line length in black (the Python formatter I hear mentioned most often). How would you feel about setting it to something really large, like 1000, to emulate having no line length limit?
- deleted 6y ago[deleted]
- gabrielsroka 6y agoI tried a few (not all) of the examples with plain old Python (granted, these are multi-liners, not one-liners, but I think they're easier to read). I'm not sure I see the advantange of curly braces. # --- Example 1 # pwk pwk 'if "braces"=="bad": { print("Be gone!"); exit(99) } else: { print("Howdy!") }' # vs # python python -c 'if "braces"=="bad": print("Be gone!"); exit(99) else: print("Howdy!")' # --- Example 2 pwk 'def s2i(s): { return int(s) } print(s2i("41")+1)' python -c 'def s2i(s): return int(s) print(s2i("41")+1)' # --- Example 3 ls / | pwk 'for s in sys.stdin: try: { print(os.listdir("/"+s.strip())) } except: pass' ls / | python -c 'import sys, os for s in sys.stdin: try: print(os.listdir("/"+s.strip())) except: pass'
- Wowfunhappy 6y agoThe advantage is the one-line versions can be easily written within the Terminal.
- neycmrtn 6y agoYou're braver than I -- whenever a shell/terminal indicates to me it expects multiline now, I press, in that order, Ctrl+C, Ctrl+D, Ctrl+Z, and Ctrl+Alt+Del.
- shenberg 6y agobeen done a while ago by forking Python (2.7.6)and modifying the grammar: http://python-with-braces.appspot.com/ http://python-with-braces.appspot.com/
- hobby-coder-guy 6y agoKurly?
- davea37 6y agoIn a similar vein, pyp: https://github.com/hauntsaninja/pyp https://github.com/hauntsaninja/pyp
- BiteCode_dev 6y agoAlso pyped (https://pypi.org/project/Pyped/ https://pypi.org/project/Pyped/).
- akdav 6y agoWhy? Please no!
- klyrs 6y agoI like python and I enjoy weirdo one-off languages, so I'm predisposed to like this. But why keep the colons? It would look nicer without. ... I just attempted to type out an example and found a reason not to do this... it's the same reason c needs parentheses around the conditional. On the balance, I prefer parentheses over the vestigial colon.
- azhenley 6y agoThere is also Bython: https://github.com/mathialo/bython https://github.com/mathialo/bython
- zmmmmm 6y agoIt's a shame Python doesn't natively support easy invocation from command line. It really shoots down a whole class of applications where bash is getting used but Python would be so much better. I've ended up using Groovy for this level of scripting, and it works really well.
- jeroenhd 6y agoIt doesn't? If I write this into a file (/tmp/test.py): #!/usr/bin/env python print("Hello, world!") and mark it as executable (chmod +x /tmp/test.py), I can just execute it as /tmp/test.py like I would do with any bash file. If you mean invocation as "execute a command that I'm passing", 'python -c' does exactly that. Even as a complete shell it works including changing directories and using standard python to do file IO, though it won't execute any system executables and doesn't do piping like you'd like from a shell. It's not intended for that purpose so I can't really blame python for that.
- black_puppydog 6y ago> though it won't execute any system executables and doesn't do piping like you'd like from a shell I think that's what xonsh was made for? :)
- deleted 6y ago[deleted]
- c-jiph 6y ago> (To the best of my knowledge, there is as of 2020 no purely pythonic way to write one-lined try-blocks.) You can do this using contexlib. For example the following in pwk: try: { print(os.listdir("/"+s.strip())) } except: pass Can be written in pure Python as: with contextlib.suppress(Exception): print(os.listdir("/"+s.strip())) (Assuming contextlib is imported, and you're okay with letting things which don't extend Exception slip through.) You could probably also make a context manager which takes a function/lambda to define how to handle exceptions etc.
- uranusjr 6y ago`contextlib.suppress(BaseException)` is possible if you really want to (although both this and the bare except clause should be avoided anyway).
- cutler 6y agoFace it - Python just ain't fit for one-liners. Give Perl and Ruby some credit as they were designed for conciseness and the command-line. Python may dominate data science, AI and ML but it's deficiencies bleed through when you try to compose something elegant and concise.
- abhgh 6y agoI agree about Perl; haven't done a lot of one liners with Ruby when I was using the language. Perl was made to be really compact to the detriment of being hard to read. I think Python strikes a nice balance, and you can compress it to a point. In discussions like these I always like to bring out my one-liner k-nearest neighbor classifier [1]! Explanation here [2] (better on a desktop). [1] https://twitter.com/AbhishekGhose/status/500564420733304833?s=20 https://twitter.com/AbhishekGhose/status/500564420733304833?... [2] http://quipu-strands.blogspot.com/2014/08/knn-classifier-in-one-line-of-python.html http://quipu-strands.blogspot.com/2014/08/knn-classifier-in-...
- xupybd 6y agoI really don't understand the love of one liners. Yes it's cool to see how much can be done in one line but it's so much harder to read. Isn't legibility far better than compactness?
- pfranz 6y agoIt depends on the context. I like one-liners because it's much easier to iterate over a command line and building them is a bit of a personal challenge since it's not worth writing a script or saving to a file. I don't know about most people, but interactively I use short flags and when writing Bash scripts I try hard to use long flags and will often break things up specifically for clarity.
- xupybd 6y agoYeah the challenge is a lot of fun I have to admit that.
- lordgrenville 6y agoOnly advantage I can think of is that you can just paste it in a shell prompt, if you're not comfortable with making a script, changing permissions, etc.
- neycmrtn 6y agoAye, in general legibility >> compactness. Apart from the intellectual exercise (fun; !work), one-liners imo come in handy in: >some_complex_tool | 'my one liner' | some_other_complex_tool > result.txt Not putting the one-liner logic into a separate script avoids an additional lookup for someone learning what is going on, along with any deployment/path/.. dependencies to that separate script.
- abraxaz 6y agoPretty nice. I love awk, but it has serious deficiencies like the lack of datetime handling and Ruby/Perl was always too fringe. I would like to see a pip package for this sometime but also maybe some consideration for integration with other previous similar attempts or other similar projects which I just learned about today.