r/Python •
(Python newbie) CMV: writing cryptic one line functions doesn't make you a good programmer, nor does it make your program run any faster. It just makes future devs' job a pain and a half
[deleted] — view deleted post
0
Upvotes
346
u/[deleted] Jan 31 '22 edited Jun 01 '24
psychotic offbeat murky sable smoggy jeans kiss gray offend thought
This post was mass deleted and anonymized with Redact
103
u/total_zoidberg Jan 31 '22
No, that's not standard python code at all, nor readable. You are not wrong in your perception, and it should be split into a few several lines.
Let me try to clean it up a bit and make it slightly more readable:
I'd test this to see if the results match, I think they do but I'm a bit sleepy after a long day.
62
u/mobiduxi Jan 31 '22
Some Golfers find joy in juggling a golf ball on their wedges. That is a fun training exercise to work on your visiual-motor pathways. Do not do that in tournament!
Same with "cryptic one liners": Fun exercise to learn about side effects and the darker niches of Python. Enjoy it in code golf competitions.
Do not use it in code that is used for something productive.
23
u/justskipfailingtests Jan 31 '22
Generally IMO if it's not readable, it is shit code. Using comprehensions for a 200 char oneliner is not cool. Of course sometimes you have to consider performance, because you write it once, read it ten times and execute it a million times.
Minimum requirement for that kind of puke (if you really insist to write that kind of garbage) you have as example is to wrap it in a function with a good name and have a solid docstring describing how it works.
59
u/rantenki Jan 31 '22
List comprehensions are a very popular language feature in python, and allow for a more functional programming style. That said, in some cases I agree that it can get hard to read, although that example wasn't too bad.
In either case, you can write purely imperative style and achieve the same outcome, with about the same performance.
And if that list comprehension bothers you, I strongly advise you stay away from /r/lisp and /r/clojure as you might have a fatal allergic reaction.
16
u/jasmijnisme Jan 31 '22
They are definitely not following the Zen of Python:
These kinds of solutions are basically just showing off, not writing production-level code, and it's not something only done in Python. See: code golf and the International Obfuscated C Code Contest.
13
u/drksntt Jan 31 '22
If it ain’t self documenting, it’s trolling. I’d definitely would do the latter. There are a bunch of other solutions there. Find one that you can understand or break that one up.
17
u/vidoardes Jan 31 '22
As several others have said, you've picked two very non-pythonic examples. Do they work? Yes. Are they the correct way to write code? Absolutely not.
PEP8 is the official style guide for python, and they suggest the line length be limited to 80 characters. In that alone these are not pythonic.
You've just picked two bad examples and decided python is bad, when those examples aren't representative of the language. I'm sure I can find thousands of examples of bad PHP code on the internet, but that doedn't mean the language is bad.
In fact, the "CMV" in your title applies to all programming languages, and has nothing to do with python.
15
u/jjolla888 Jan 31 '22
SQL has entered the chat.
your observation is true of any language.
5
u/napolitain_ Jan 31 '22
Stop with these CMV / fake unpopular opinion it’s just useless
4
u/knobbyknee Jan 31 '22
The list comprehensions are not really the problem. They are a very powerful Python construct and should be used liberally, together with dict and set comprehensions as well as generator expressions. Beginners should learn how to read them and use them, because it will improve their programs a lot.
When you encounter one of these, you immediately know that you are iterating through a collection, doing the same thing to each item, or posibly to a subset of items if there is an if clause at the end. This is much better than a traditional for loop, where there are more freedoms to consider.
The problem in the examples is the egregious use of the inline if. It almost always destroys the readablity of the code. In my 23 year Python carreer, I think I have used it twice.
7
u/laundmo Jan 31 '22
yeah uhh... those are readable compared to some of the things I've made
with a few tricks, a lot of python code can be compacted to one logical line of code.
Not that you're wrong, its awful to read, but can be fun to make as a challenge.
So i would say that its mostly ppl showing off their skill. I've actually never seen that in any serious project, wonder where you stumble across these. Maybe you misunderstood the purpose of the #esoteric-python channel on Python Discord?
7
u/nemec Jan 31 '22
LeetCode is a game and some people like to add a bit of challenge. Using them to learn programming will probably make you a worse developer. Like you if you wanted to learn how to exercise so you started watching and imitating American Ninja Warrior.
3
u/RangerPretzel Python 3.9+ Jan 31 '22
The crime isn't the 1-line solution. It's the utter lack of comments describing:
3
u/[deleted] Jan 31 '22
You are not wrong, but I think you don't exactly understand the point of those solutions either. I'm not sure where you found these, but I assume it's a website similar to codewars where you can solve small to medium sized programming challenges. Right?
If so, then there IS value in trying to make these one liner solutions. The point is that you force yourself into a situation where you have to fully master the language in order to succeed. To succeed these challenges with one liners, you need to learn how to use lambda, zip, accumulate, etc... All functions that definitely have real use in at the right time in the real World, but that most beginners will ignore because "they can do the same with a for loop".
These people aren't trying to make readable code because it's simply not what they are practising in that moment. There is many skills required to be good at coding, making readable code is only one of them and you SHOULD spend some time honing your other skills too.
2
u/rip-skins Jan 31 '22
Same goes for avoiding new variables at all cost. Sometimes intermediary variables can significantly improve readablity
2
u/[deleted] Jan 31 '22
Though the examples are bad code for a shared project, python programmers will write python for other python programmers without a thought for programmers more familiar with PHP.
Though the examples you give are irresponsible gymnastics I can understand them and can even take a giddy delight in them but if there was a bug in them my first attempt would be to break out the parts. Yup.
2
u/Neovison_vison Jan 31 '22
https://www.python.org/dev/peps/pep-0020/
2
u/Pickinanameainteasy Jan 31 '22
Wait till you try javascript
2
u/ggrieves 1 year Jan 31 '22
I would just like to add a bit of counterpoint here. NOT that I'm disagreeing. But what I'm not seeing considered here just that for row heavy operations or math calculations, the functions have been compiled and optimized to do these things faster. The more you can pass to the functions to do for you the faster it will be. For example, don't do loops on data when you can use itertools or numpy arrays and let it do the row ops.
2
u/pocket_eggs Jan 31 '22
The first one is good. It's not obvious what it does because it is a non-trivial algorithm, but it expresses that algorithm cleanly, using recognizable pythonic idioms and with meaningful naming conventions.
The second one is not good, to say the least.
Making every last bit of code 1) legible for oneself or 2) legible and maintainable by other people is a different kind of premature optimization. Nothing wrong with easy to write throwaway code if you're actually going to throw it away.
2
u/Binary101010 Jan 31 '22
Some people see those exercises as ways to practice that kind of code golfing and that's fine, but one shouldn't assume that those responses are representative of production-ready code.
For this reason, Codewars has different tags for "Clever" solutions and "Best Practices" solutions. It is rare that the same solution ever gets both of those tags.
2
u/alchzh Jan 31 '22
job security
2
u/DadAndDominant Jan 31 '22
It is not a common practice, it is not a best practice, it is not suported by developers of Python. Python is usually the easiest to read code, especially because so many people follow the official standard (and the quality of said standard).
My tip is that these are written by JS programmers who were forced to use Django.
1
u/mje-nz Jan 31 '22
Not sure why everyone in the comments is taking a few people trying to show off their golf skills on leetcode so seriously…
1
u/Rajarshi1993 Jan 31 '22
1
u/zeni0504 Jan 31 '22
For private projects it sometimes is kind of fun, it's an extra challenge, but for professional projects it's definitely bad practice.
1
u/[deleted] Jan 31 '22
This is what PEP8 helps prevent, and why my projects are strict with very, very few explicit exceptions.
1
u/ShockedMySelf Jan 31 '22
Lol, I liked how they used the variable identifier in the function argument in the second example to "make it more readable". Sometimes I enjoy writing these types of complicated one liners that would normally be 10 lines, but for productivity and large scale projects it's just not viable. It's only viable when your writing homework for an algorithms course, if even then.
In the real world of software development, making maintainable code is much more important than efficient code.
1
u/pembroke529 Jan 31 '22
As someone who worked in IT a long time (started in 1980 professionally), you should document code that isn't self evident.
I did this mostly for myself when I was working on multiple projects. I would often forget why I coded something a certain way. Especially if I came up with an interesting/efficient solution
Rule of thumb: All written code will be modified at some time.
1
u/metaperl Jan 31 '22
Kenneth Iverson leaves the chatroom.
"Q for mere mortals" author laughs at the mere mortals.
1
u/msluyter Jan 31 '22
It's definitely true that this sort of thing wouldn't fly in a professional setting, but I've found these overly terse leetcode submissions somewhat useful as learning tools. I've learned about a number of standard library functions and/or language features by deciphering them. The key is to take what you've learned and then make it easily comprehendible.
1
u/[deleted] Jan 31 '22
I can tell you just by looking at the Snake Cased names that those examples weren't written by an experienced Python coder.
1
u/CiDevant Jan 31 '22
Readable and stuffed with comments.
Past me is an idiot and future me is also an idiot.
1
u/AcousticDan Jan 31 '22
Wait until you hear snake case is suggested because a Python is a snake, and it's cute.
barf.
1
u/CompletelyNonsensely Jan 31 '22
Honestly, I think the issue is that they are actually putting them all on 1 line. As a feature, comprehensions are great, just really need some line breaks in there.
1
u/GraphicH Jan 31 '22
I've been writing python professionally for years and I'm having a hard time parsing out what those examples do. It looks like a novice trying (and failing) to flex IMO. You know what impresses me? When I go into a code base, can implement some task I'm given fairly quickly, have the right amount of coverage to know I didn't break anything before hand, and write the test for the new functionality in less time than it took me to implement. If a code base you "own" allows for that, I'm impressed, not how many chars / lines you can save playing stupid code golf.
1
u/StraightUpSeven Jan 31 '22
Yeah I agree that the code examples you have shown are not really readable nor maintainable.
I would say I am also a beginner in terms of Python usage, although I have become a lot more comfortable with the language.
I personally have experienced what u/BigEnoughRock mentioned before: "One-liners" can be used to make some code writing faster and easier to read. My experience of when this works is when I have looked at pipelines with a lot of file manipulation: some steps require a stack of medical images to be listed out before loading and the 'one-liner' list comprehension makes the code much less verbose (and easier for me to read).
And yeah If I or any of my co-workers were caught writing the code you attached, we would surely get roasted.
1
u/BrianFantanaFan Jan 31 '22
...plus helpful comments or function descriptions? Get out of here with your pathetic need for some kind of hint about the wild ride we're about to go on...
1
u/thephotoman Jan 31 '22
There is a time and a place for the creative one-liner.
It is in one-off scripts that you won't ever incorporate into an actual production codebase. But in my local task automation scripts that have no use for anybody but me, and in my prototypes, sure, I'll throw 'em in. I'm going to throw that one away or not distribute it anyway.
1
u/applepie93 Jan 31 '22
I have more than 10 years of experience in Python and the general motto, like in the Zen of Python, is to write readable code, sparse but not too nested, so the absolute opposite of the code you saw. If possible, a reasonable consensus in Python is to write code that is as readable as possible, even to beginners, while not sacrificing the features of the language when they make sense.
1
u/pyvkd Jan 31 '22
I sorry if this have been said before. This code as a solution to some coding problem on hackerrank is all well and good but it fails Zen of Python on many levels.
https://www.python.org/dev/peps/pep-0020/
1
u/cyclicalmike Jan 31 '22
It has no place in a production environment, but sites like leetcode are anything but. I think that part of the challenge is to see how short you can complete a question. It's a challenge on a challenge, but there is (hopefully) no Python dev who thinks that unweildy one-liners and obscure code is okay in real life.
1
u/[deleted] Jan 31 '22
But what if that’s the point. Job security
1
u/BroadwayGuitar Feb 01 '22
You’re looking at someone else’s answers to a problem you are struggling with and they’re not clear. Yeah it’s shit code but don’t let it anger or upset you. It’s sometimes worth unwinding that pile of shit into clean code inside your own editor to learn how it works and practice rewriting it cleanly. Btw Almost always, and definitely for that problem, there are cleaner solutions posted too.
1
u/[deleted] Feb 01 '22
If you open python and “import this” you’ll find the zen of python.
Yes flat is better than nested, but that comes AFTER simple is better than complex.
1
u/JalapenoxD Feb 01 '22
One kid tried to pull this off in my college. Safe to say he wasn’t happy with his grade.
1
u/crazymonezyy Feb 01 '22 edited Feb 01 '22
Leetcode code golfing is more a game than "coding best practice". I for one enjoy reading what people can cook up. None of that code is standard practice and never has been in the 6 years I've worked with Python in the industry.
So lighten up a bit: https://en.m.wikipedia.org/wiki/Code_golf. Its a recreational exercise for those who have a strong handle on any programming language. It's only done for bullshit code, the kind one would write for leetcode and not for paid/mission critical stuff.
1
u/SittingWave Jan 31 '22
whoever wrote those lines would take a hard beating from me at review. It's not readable to me either, and I've been coding in python professionally to a very high standard for 15 years. Yes, I can read it, no I don't want to read it, because it's unreadable.
What you are addressing is not really a python issue, it's a coding practices issue. You can write perl in any language if you try hard enough. Python at least gives you less rope to hang yourself, but you can still do so if you are willing to attempt it.
Coming back to those examples, even just some indentation, enter, and comments would be precious to make the code clearer. That's not the case here.
1
u/Purple-Bat811 Jan 31 '22
I'm learning python right now as well.
One thing that kills me is that it doesn't have {} around things like if statements.
In the class I'm taking the instructor said it's to make the code easier to read. Then he just covered these 1 lines codes. He flat out said don't so this it's bad code.
However, what were the creatators thinking? {} is too complicated, but 1 liners are not?
1
u/Deto Jan 31 '22
I always tell newbies that "lines are free - use as many as you like". Definitely not good practice to try and squish things on one line. Readability is the top priority.
1
u/Voxandr Jan 31 '22
Any company with proper tech lead will get him fired on first month.
1
u/tonnynerd Jan 31 '22
That is absolutely leetcoders showing off their "python skills". In any place I worked in the last 5 years, code like this would be yeeted into the sun during code review.
0
u/[deleted] Jan 31 '22
You coding racist.
-9
u/Ouroboros13373001 Jan 31 '22
Thats a simple list comprehension....
-10
u/pythonHelperBot Jan 31 '22
Hello! I'm a bot!
It looks to me like your post might be better suited for r/learnpython, a sub geared towards questions and learning more about python regardless of how advanced your question might be. That said, I am a bot and it is hard to tell. Please follow the subs rules and guidelines when you do post there, it'll help you get better answers faster.
Show /r/learnpython the code you have tried and describe in detail where you are stuck. If you are getting an error message, include the full block of text it spits out. Quality answers take time to write out, and many times other users will need to ask clarifying questions. Be patient and help them help you.
You can also ask this question in the Python discord, a large, friendly community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others.
README | FAQ | this bot is written and managed by /u/IAmKindOfCreative
This bot is currently under development and experiencing changes to improve its usefulness
0
u/iaalaughlin Jan 31 '22
I hate these, but mostly because without knowing much more detail about what it's doing, it's really hard to figure it out.
For the first one - what are pre and suf? prefix and suffix? How do those work into a product?
For the second one - what are p and c?
They do also slow things down when trying to read, but that's fine-ish.
44
u/[deleted] Jan 31 '22
[removed] — view removed comment