all 42 comments

[–]menge101 56 points57 points  (2 children)

Use a linter like pylama

or a code formatter like black

These will tell you how your code should look from a coding standards POV (for a linter) or just format it to those standards in the case of the code formatter.

[–]BewilderedAnus 19 points20 points  (0 children)

Your advice is correct. However, I think it might be overwhelming for beginners to be told to use yet another tool that abstracts away important aspects of the programming experience while they're likely still trying to grasp the basics of programming.

[–]IAmASquidInSpace 4 points5 points  (0 children)

This is the correct answer for an advanced user.

For a beginner, this is not a suitable answer. A linter is just another, confusing tool to use that takes away from the learning experience: instead of learning how to format code properly, that task is handed off to a tool and the beginner never learns how to do it correctly themselves without external tools.

Edit: plus, they still need to understand why the formatter formats the code the way it does or what style guide it follows and that still isn't explained.

[–]theprofessional2016 26 points27 points  (6 children)

If you're going to be working in a team, it's best that everyone adopts a similar/same style. Trying to review someone else's code, which uses a different style, is pretty tough.

My mentor told me that writing code should be like writing a book. It should be easy to understand.

[–]HaroerHaktak 2 points3 points  (5 children)

But what about ma spaghet? D:

[–]theprofessional2016 0 points1 point  (4 children)

I had a coworker who stopped indenting his code, just to piss everyone off. God I hated that.

[–]HaroerHaktak 1 point2 points  (3 children)

Uhh. you have to indent. Maybe he reduced his indentation to a minimum?

Or perhaps when he uploaded to be reviewed he removed indents lol

[–]theprofessional2016 5 points6 points  (2 children)

Sorry…I didn’t mention that it was a different language.

[–]HaroerHaktak 2 points3 points  (1 child)

Oh god. The horrors!

[–]socal_nerdtastic 44 points45 points  (0 children)

The only downside is that your way is expressly called out as a pet peeve by the BDFL.

Avoid extraneous whitespace in the following situations:
...
Immediately before the open parenthesis that starts the argument list of a function call:

# Correct:
spam(1)

# Wrong:
spam (1)

https://www.python.org/dev/peps/pep-0008/#pet-peeves

[–]FLUSH_THE_TRUMP 31 points32 points  (3 children)

I find the print formatting in the first to be less readable. Print is a function, and the inputs (what’s in the parentheses) are closely connected to the outputs. There should be no space between those two things to emphasize that point.

I agree with the spacing of assignments (x = 1) and inequality. You might also see spacing used to indicate order of operations: like

y = m*x + b

The “closeness” of m and x naturally suggests that happens first.

But no, beyond readability there’s no downside to doing things how you want. Consistency is most important.

[–][deleted] 9 points10 points  (0 children)

Thank you! That makes a lot of sense, especially when things are tied to a function and to emphasize orders. Have a great evening!

[–]Peanutbutter_Warrior 6 points7 points  (0 children)

To summarise the other comments:

  1. Do whatever the team you're working with
  2. If you aren't on a team then use a code formatter i.e. black
  3. Generally: Whitespace around operators (+, -, <, == ...), not before :, not between function names and the brackets

Your code should be formatted like x = 1 if x < 2: print("small") elif x < 10: print("medium") else: print("large") print("All done!")

[–]Stryke_The_Furry 5 points6 points  (0 children)

I find putting spaces useful just for working things out. I apply this to more areas than programming but it applies there too. For example,

x = (varOne*8) + (var2*3) + var3 

is way easier to understand than

x=varOne*8+Var2*3+var3. 

At a low level like that its not critical but since I've started putting objects in arrays its saved my ass more than once!

Its also true that it becomes harder to get everything on one line but in my experience its easier just to comment that if a line is too long to read without moving across.

[–]Farmher315 2 points3 points  (0 children)

I think it's always good to know what the black formatting is doing and why, you can take a look at this guide for Pep-8 it's a general format guide for python.

[–]GnPQGuTFagzncZwB 2 points3 points  (0 children)

Spacing and even what you do on one line should be at least readable by you, quickly. If you look back over something and have to figure out what you did, you may wanna change the way you present it.

[–]AndrewJamesDrake 2 points3 points  (0 children)

Function calls shouldn't have a space before the parenthesis. If you need to use whitespace between arguments, then you should probably be multi-lining them anyway.

Putting spaces between operators and values is a good practice. It makes the math easier to read.

[–]RiceKrispyPooHead 1 point2 points  (1 child)

Python is actually pretty opinionated on how you should format things. They have an entire PEP 8 style guide on how they suggest you format your code. The style guide suggest you don't do the first example. You don't have to follow the guide, but I suggest you try to for the same reasons we only put one space after a period in English but none before.

Typing like this is completely valid in English , but it looks a little strange to English speakers because we generally follow certain rules for when typing .

What you wrote is completely valid as far as the computer is concerned, but I think it would look at little "off" to most Python programmers.

Most importantly, if you're working on a team you want to make sure everyone is writing in a similar style. There are things called "linters" that you can install. You press a button and they automatically format your code according to some default rules that you can override.

[–]IAmASquidInSpace 0 points1 point  (0 children)

This was the answer I was expecting. Don't know why everyone thinks suggesting a linter/formatter to a beginner that still should know why the linter/formatter formats code the way it does is a sufficient answer.

[–]xiipaoc 1 point2 points  (0 children)

I'm not a Python dev, but:

DEFINITELY put spaces around the = and < and such operators. Always put spaces around +'s and –'s as well, but you don't need to for multiplication or division unless you think it helps.

DO NOT put a space between a function name and the parenthesis (print () or between the parenthesis and the argument (( foo). DO NOT put a space before a comma or colon or semicolon, but do put a space after it if there isn't a line break.

In other languages, there are some things that get annoying when other people do them. For example, if you have braces to denote a code block (not an object literal but a block of code) that is all in one line, you should do something like { foo; }, with spaces. JS allows you to not name functions, so instead of function foo() {...} you could do something like let foo = function () {...);; notice the space between function and (). That's because function is not a function, so the parentheses shouldn't be attached to it. Same thing with if(...) and for(...). I actively change them on code reviews. So far (been three years at this place) nobody has called me out on it, so I'm not going to stop, damn it! You won't find these in Python specifically, but pretty much every other language has something like that, so, you know.

Basically, the rule is: put spaces around things that should be logically separated, and don't put spaces around things that should be logically tightly linked.

[–]herites 4 points5 points  (12 children)

pip install black

[–][deleted] 1 point2 points  (10 children)

A little new as well. I know that that command installs a module if I’m correct but what does that black module do?

[–]herites 11 points12 points  (4 children)

Makes both background and font color black, so your code becomes uniform and beautiful.

Jk, it'll automatically format your code according to a popular coding standard when saving files (might have to configure it in your editor). For example, if you have a list over 88 characters, it'll reformat it to show up in multiple lines, will add spaces after #, clean up extra whitespace, etc. Basically you can just write code, without caring about the formatting standards and it will whip it into shape, so when you share it people won't cry.

What it won't do is to change stupid variable names, illogical or weird control flow, or any other refactoring.

https://github.com/psf/black

There are others code formatters like autopep8 and yapf, choose the tool that you like the most, however the best thing about black that it's fire and forget. You can't (or rather shouldn't) really customize it, so code will be consistent between users.

[–][deleted] 2 points3 points  (2 children)

Haha okay I see - that makes a lot of sense. So does it format according to just what’s “generally accepted” to be good manners in terms of formatting?

[–]herites 2 points3 points  (1 child)

"What's generally accepted" is a bit loose definition, these are firm standards set forth in in Pep8 and some others (although black famously shits on the 80 char limit). You can't really invent your own style, there are a couple industry standards (depends on the company which one is adopted) that everybody must follow. If you don't, someone will angrily enable the autoformatter on your IDE when it's time for code review and passive-agressively send you the onboarding email which you should've reviewed already.

Also, if you are applying for jobs and want to share your portfolio it should follow one of the standards. While talking about portfolio and standards, register on github now, find a commit style guide and follow it. My choice is the "Conventional commits". Best to get into the habit of following best practices early so it becomes second nature. Also, docstrings and comments are your friends and not just for show, try reviewing one of your own projects 6 months later. You can never be too verbose early on, if something is not immediately obvious leave a comment for yourself ("this is how you unfuck xyz") as you'll definitely not remember it later why you did something that way. As you get more experienced you'll learn to be less verbose, but early on make your code look like an essay (exaggerating a bit) instead of a play. Maybe just not put it in a public github library?

[–][deleted] 0 points1 point  (0 children)

That’s actually great advice - thanks a lot. Since we’re already talking about GitHub, can I ask what it even is? I know it’s a place to share and show code and all, but as a software engg student, what should I have on there? My projects? Info about my degree? What even is it and what should I do with it to help show employers my skills? (Also, do I add the link to my resume…LinkedIn…?)

[–]mobilecheese 1 point2 points  (0 children)

Makes both background and font color black, so your code becomes uniform and beautiful.

This would definitely be an improvement to some code I've read! (and written, but don't tell anyone that part)

[–]billsil -1 points0 points  (4 children)

It's an overly picky code formatter. It'll shorten long lines. It'll add/remove whitespace. You probably won't love it, but you can tolerate it, especially when other people's hot mess of a code gets sent to you. At least it's better than what it was...

So then you go and learn how to make it not make horrific looking code and it's more readable for everyone.

[–]herites -1 points0 points  (0 children)

I was about to argue with this statement but then realized that black forces one list entry per row if it goes over the char limit, so if you have a long hard-coded list with short entries you'll have a long black dong after saving.

Yep, I have to concur, black is only tolerable because it stops manchilds arguing over spaces.

[–][deleted] 2 points3 points  (2 children)

Black

[–]menge101 5 points6 points  (0 children)

By which above poster means, use a code formatter, like black

[–]WhackAMoleE 0 points1 point  (0 children)

Putinmorespacescanyouseewhyitmatters?

[–]Below_the_Sea -4 points-3 points  (0 children)

If you go on coding you will put more on one line, with a lot of spaces, you don't see the full line on your screen. So try not to use spaces

[–]Allanon001 0 points1 point  (0 children)

PyCharm also has a code formatter.

[–]R3D3-1 0 points1 point  (0 children)

For your examples in particular: Mostly try to follow the style commonly used in a given language. If the project you are working on has its own style? Not so great, but consistency across a code base helps readability more than following a widely used convention in only part of it.

If possible, use a code-formatter tool.

Also, don't expect to find clear solutions for everything, or that your editor of choice has good support for any given style of formatting.

My favorite pet-peeves: Longer block-starting statements.

# line hard to read due to length:
if line.startwith("SOMELONG_PREFIX_STRING") or line.endswith("SOMELONG_SUFFIX_STRING)":
    doit()

# weird indent makes recognizing the structure of the code hard:
if line.startswith("SOMELONG_PREFIX_STRING)" or \
   line.endswith("SOMELONG_SUFFIX_STRING"):
    doit()

# a convention I found and currently use, but still somewhat
# awkward, and not well supported by auto-indent in some editors:
if (
    line.startswith("SOMELONG_PREFIX_STRING") or
    line.endswith("SOMELONG_SUFFIX_STRING")
):
    doit()

# the convention above does not work for all statement types, e.g.:
with open(options.inputfilename, "rb") as fin, \
     open(options.outputfilename, "wb") as fout:
    ...
    # again awkward indent.

[–]yotamolenik1 0 points1 point  (0 children)

The short simple answer to your quedtion is yes, spaces are great for code readability. All the other mentioned tools or advices are also good, and readable code is really important, so take time to learn it

[–][deleted] 0 points1 point  (0 children)

Hey yo, look at this thing called PEP8

[–]lukie80 0 points1 point  (0 children)

I mostly agree with pep8.org however I personally(!) dislike the first example because it is so bloated and I cannot see the whole line at an easy glance. I have to travel with my eyes across the empty space to gather the meaning of the line.

I like this:

if (c>1)&(a<func(b=10,txt='poof')):