Jump to content

Commenting in code Python

Tehkast

Evening all,

 

Just curious to speak to anyone with more knowledge.

 

I'm in the learning process of programming with hope to turn into a job.

 

Something Luke said on the WAN show yesterday caught my attention was mentioning comments.

 

As I've only ever written code for myself and learning and no major projects never really bothered with comments was more used when making notes in examples.

 

Is adding comments something really should get into the habit of asap? What is a useful comment vs a obvious one as that seems very subjective.

 

Any thoughts most welcome and hope all having a great weekend 🙂

 

Link to comment
Share on other sites

Link to post
Share on other sites

It's difficult to come up with a hard and fast rule on what should or should not have a comment. In many cases if you've written your code sensibly another programmer can tell what it's doing without comments explaining everything. When you need to comment is something you'll develop a feel for as you write more, and especially once you start reading other people's code, or even your own old code you've since forgotten. If you're reading code and stop to go "wtf is happening here?", that's probably somewhere that could have used a comment.

 

I've got some examples of places I tend to put comments:

 

One to explain each function, even if what it does is fairly trivial, and especially if it's going to be part of a library.

 

One to mark weird workarounds or corner cases, so someone else doesn't walk into the same problems "fixing" your troubleshooting, the more strange the workaround or issue the more it needs a comment.

¯\_(ツ)_/¯

 

 

Desktop:

Intel Core i7-11700K | Noctua NH-D15S chromax.black | ASUS ROG Strix Z590-E Gaming WiFi  | 32 GB G.SKILL TridentZ 3200 MHz | ASUS TUF Gaming RTX 3080 | 1TB Samsung 980 Pro M.2 PCIe 4.0 SSD | 2TB WD Blue M.2 SATA SSD | Seasonic Focus GX-850 Fractal Design Meshify C Windows 10 Pro

 

Laptop:

HP Omen 15 | AMD Ryzen 7 5800H | 16 GB 3200 MHz | Nvidia RTX 3060 | 1 TB WD Black PCIe 3.0 SSD | 512 GB Micron PCIe 3.0 SSD | Windows 11

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Tehkast said:

Is adding comments something really should get into the habit of asap?

Yes. Even if that code is just for you, comments can help you recognize what the code does months or years down the line.

1 hour ago, Tehkast said:

What is a useful comment vs a obvious one as that seems very subjective.

Maybe try to think of it this way, will someone who sees your code for the first time understand what it does without you having to explain it to them?

Of course, you don't have to write paragraphs (unless it's very complicated; has a lot of abbreviations for example), keep it simple but understandable. This way, you can quickly know what a function or object does without having to retrace your steps.

1 hour ago, Tehkast said:

with hope to turn into a job

If you hope to work with other people, then comments will really come in handy and can save a lot of time in the long run (not having to set up a meeting to explain what everything means/does)

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, Tehkast said:

As I've only ever written code for myself

Most jobs are in teams, but it's excellent to learn to do things for yourself instead of requiring a team.

4 hours ago, Tehkast said:

and learning and no major projects never really bothered with comments was more used when making notes in examples.

Awesome.

4 hours ago, Tehkast said:

Is adding comments something really should get into the habit of asap?

Yes; anytime you write confusing code or use something complicated, write as many comments as you need to explain things.

4 hours ago, Tehkast said:

What is a useful comment vs a obvious one as that seems very subjective.

So you know python, but not C, however if you read this code, you'll know exactly what a function like this will do:
 

int Square(int value){
  return value * value;
}

 

This is what some may refer to as "Self documenting code." This is code that more or less documents itself. When you square something, well, what's the math?

Most people should understand some intermediate level math like squares and pythagorian theorem. If you learned it in middle school or high school, you should pretty much know it.

 

So when you write code, you say "How easy is it to understand this code in about 30 seconds?" The above method is basic C math logic, short as it fullfills a single purpose, and the method is self explanatory.

 

Let's pretend the Pythagorian theorem is super complex scientist mathematics and you write this method knowing you're a math guru:

int GetHypotonuse(int a, int b){
  int c = Square(a) + Square(b);
  return SquareRoot(c);
}

Quite a few things going on here & you're using a few math libraries with Square and SquareRoot.

You might put a few short comments here like so:

//Uses Pythagorean Theorem.
//A^2 + B^2 = C^2
int GetHypotonuse(int a, int b){
  int c = Square(a) + Square(b); 
  return SquareRoot(c); //Square root is how you undo a power of two. 
}

First comment "Uses Pythagorean Theorem" tells them the algorithm you used. If they really want to understand this method, (say it was incorrect) then another colleague can research the Pythagorean Theorem if he is unfamiliar.

 

The second comment has the algorithm. Since it's a simple algorithm, it's nice to share it. However, because you said that it is the Pythagorean theorem, if they need to know the details of what A B and C are, they can research that because you gave them the name of the algorithm.

 

The third comment goes over something a bit more complicated. You have C in the first line of code, but it's not the correct answer because it needs to be square rooted. Square rooting is not in the algorithm you posted, so explaining what you did and maybe why (I didn't explain why, only what I did) so people less understanding of what's going on could see why you did things.

 

 

So in summary, comments are usually used for complex things.

As others have explained to me on this forum & the conclusions I reached when talking to others is:

1. Expect people to know the language. Don't explain if statements.

2. Lots of code documents itself.

3. Use comments to give a briefing on complicated methods.

4. Use comments to explain why you did weird things.

5. When in doubt, drop a comment. The worst that happens is you lose 2 minutes to writing a comment that won't be used for 5 years.

 

It's better to have more comments, than less in most instances. If you comment every line or most every line, you're likely doing something wrong.

4 hours ago, Tehkast said:

Any thoughts most welcome and hope all having a great weekend 🙂

you too!

Link to comment
Share on other sites

Link to post
Share on other sites

19 hours ago, Tehkast said:

Is adding comments something really should get into the habit of asap?

Comments and more importantly code documentation is definitely something you should get into. Even if you're just writing code for yourself, you'll be surprised just how much you can forget a month or two later. Especially if you're writing a lot of code.

 

19 hours ago, Tehkast said:

What is a useful comment vs a obvious one as that seems very subjective.

To give an example:

// returns value
public int getValue() { return value; }

That comment doesn't tell you anything you can't see at a glance. In other words it's useless. Leave it away.

 

I rarely write comments in code itself unless that code is difficult to understand (in which case you should probably rewrite it to be more clear). E.g. if there's a complex algorithm and there's no way to make it more obvious, then yeah, write a comment. Or if there's something that, at first glance, looks like a mistake, explain why it has to be that way to prevent someone else (or yourself in the future) from "fixing" it only to find out (or remember) it was intentional later on.

 

I do tend to write a lot is code documentation (comments that describe what a method does, what arguments it takes, what it returns, which values it accepts, which exception it can raise and so on). Write the comment for the person calling that method, not the person writing that method. Assume the person doesn't have access to the code and doesn't necessarily understand the concepts behind it.

 

To stay with the above code example, this is how I would document the hypotenuse method (I'm mostly a Java-dev, so please excuse the use of Javadoc syntax):

    /**
     * Calculates the length of a right-angled triangle's hypotenuse.
     * <p>
     * The hypotenuse is defined as the longest side of a right-angled triangle; the side opposite
     * of the right angle. Its length can be calculated by squaring the length of the other sides,
     * adding them, then calculating the square root.
     *
     * @param a the length of one of the triangle's sides touching the right angle. Must be a
     *          positive non-zero value.
     * @param b the length of the triangle's other side touching the right angle. Must be a
     *          positive non-zero value.
     * @return the square root of a² + b².
     * @throws IllegalArgumentException if {@code a} and/or {@code b} is zero or negative.
     */
    public double hypotonuse(final double a, final double b) {
        if (a <= 0 || b <= 0) {
            throw new IllegalArgumentException("a and b must be positive");
        }
        return Math.sqrt(a * a + b * b);
    }

Most code documentation I write follows the same basic structure.

  • The first sentence of the documentation (essentially its "caption") gives a quick overview of what the method does. For anyone familiar with basic geometry this should be enough. They'll read that line and can move on.
  • In case the person reading the documentation is not familiar with triangles or needs a refresher, there's information in the comment body for them to understand the basic concepts without having to consult a math book.
  • The return value is a quick technical summary of the value you'll get back. If someone isn't interested in the "why", they can just read that line and immediately understand what result they can expect.
  • The @param(s) tell you what values are expected of you and what is and isn't acceptable and finally the @throws tells you the consequences of providing incorrect values.

When you're working in a team, keep in mind that not everyone has the same skills and knowledge as you, not everyone has the same background. The other person may be a good developer, but might have forgotten (or never learned) much math. There will also be new people who will be asking a lot of "obvious" questions, simply because they're not as familiar with the code base as you are, or because they are new to programming in general.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

22 hours ago, Tehkast said:

Is adding comments something really should get into the habit of asap? What is a useful comment vs a obvious one as that seems very subjective.

You have to think about who is going to read your code. If you're writing hobbyist code it'll be Future-Tehkast, and if you're writing in a shared project it'll be other developers.

 

In either case, the person reading your code will have no clue what you were thinking when you wrote it. A good comment is something that another dev working on the project, or you a year from know could read and understand what the function is doing. 

 

22 hours ago, Tehkast said:

I'm in the learning process of programming with hope to turn into a job.

Part of this process is going to be learning about commenting. A year from now, you'll come across some problem and remember you've solved it before. Then you'll open up your own code and think "what in the world was I doing here?". Or maybe you'll search for some problem and come across an answer on a forum which contains code "that works" but where you have no idea why it works. These are the moments where you learn the value of comments.

Link to comment
Share on other sites

Link to post
Share on other sites

As others have said, commenting is always a positive and has to be thought of from some different perspectives.

1. Commenting for yourself:

 

While working on a project, as you're learning and implementing functions and ideas and problem-solving your code, you're likely to have everything be top of mind as you go through your files, so you think less of explaining it to yourself. However, should anything ever take you away from your project, or you re-visit the project for another reason in the future, there will invariably be times when a snippet you hacked together with a solution from some Google searches won't jog your memory as to what your intended purpose was.

Adding comments for what you were trying to do (whether or not you know what all the code is doing) is helpful, as is including the URL where you found a solution or snippet that you were able to customize.

 

2. Commenting for others:

 

The easiest way to think of this, as you state you're starting to learn programming for hopes of a future job, is imagine opening any project as a beginner and there being no documentation/comments at all. Most would be pretty lost outside of the simplest early tutorials.

Sure, plenty of programmers know their language and the syntax, variable types, functions, etc... but in the case of projects that incorporate multiple libraries, import functions, databases and files, keeping track of what is part of what becomes cumbersome quickly over thousands of lines of code. 

As Eigenvektor points out, a comment like "// returns value" is useless. If the code is complex, you might need extra comments throughout to highlight what is occurring at each step, or what the goal is of the function, or operation, etc. If it's relatively simple, just a comment before it starts generally suffices.

And as Eigenvektor also points out, the skill and experience of programmers will vary widely on a project. In an established team, there will be a codebase and certain structure to things in regards to set functions, and libraries and other things. To a brand new person, whether coming from school or from another company, the expectations or scope of the project might be completely different. Having no documentation will force a lot of questions from the new person until they can get up to speed and learn the nuance.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 6 months later...

yes, it increases readability, and can be used as documentation

its easy for maintenance and for the other developers working on your code

it will also be easier for you to debug

 

and too much comments for even the slightest things are just basically useless, like

# add values in variables and b and store it in c
c = a + b

if you are using python, you can also use doc strings to document functions like this,

def pythagorean_theorem(a, b):
    """
    Calculates the length of the hypotenuse of a right-angled triangle
    using the Pythagorean theorem.

    Arguments:
    a -- length of the first leg of the triangle
    b -- length of the second leg of the triangle

    Returns:
    c -- length of the hypotenuse of the triangle
    """

    # Calculate the square of the length of each leg
    a_squared = a ** 2
    b_squared = b ** 2

    # Calculate the square of the length of the hypotenuse
    c_squared = a_squared + b_squared

    # Take the square root of c_squared to get the length of the hypotenuse
    c = c_squared ** 0.5

    # Return the length of the hypotenuse
    return c

 

hey! i know to use a computer

Link to comment
Share on other sites

Link to post
Share on other sites

I feel like this really encompasses the moment you know there was a missed opportunity for some helpful comments :

image.jpeg.7d08403c9c8aefb01428a417b83bf84b.jpeg

 

Small, simple projects don't often require much in the way of commenting and getting caught up in commenting too much can tend to be used as a crutch for unclear code with poorly chosen variable names. More than any specific habits around commenting, being able to clearly explain your code, especially why it is structured the way it is and choices of algorithms/data structures etc. is going to help moving into a professional setting (both during interviews and when actually working). Writing documentation for what you are doing can be help you get used to explaining and thinking through these sorts of choices, but code comments aren't the only or even usually most important documentation... overall, most new developers would probably get as much or more value focusing on versioning/defect logs/commit comments,  req. (user story etc.)/arch. (functional interface/class diagrams) / end-user documents than code comments. Not a big fan of TFD in production, but think TFD approach is great for learning and tends to clarify what needs to be documented. 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...
On 8/20/2022 at 10:45 PM, Tehkast said:

Is adding comments something really should get into the habit of asap? What is a useful comment vs a obvious one as that seems very subjective.

Definitely add some comments as they are both good for you looking back at your code, and others looking at your code.

 

Comments allow you to write down your thoughts and notes as well incase there are any features you might want to add in the future but can’t at the moment for whatever reason. It’s definitely something to get into the habit of.

 

 

An example of an obvious comment would be writing “// importing os module” right above your line of code: “const os = require(‘os’);”. A more obvious example would be commenting, “# importing tkinter” above “import tkinter”.

 

 

Comments are best used to describe something that might not be clear in your code, especially if it’s messy code. Anyways hope that helps dude and good luck!

Link to comment
Share on other sites

Link to post
Share on other sites

Use javas oracle doc as good example of code commenting standard. 

Sudo make me a sandwich 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

Personally I find that self documenting code is better than just commenting. Although I do have peers who are strict in not using comments at all I personally think comments are handy at times. Instead of comments, group parts of code together in a method/function and give it a good descriptive name. Comments in my opinion are for things which aren't obvious or common knowledge and cant be fulfilled with a simple name. Python has documentation comments/docstrings which will enable certain features on some IDEs, These I think you should always do, this makes APIs more descriptive for others using it. As for actual code, to avoid the subjective parts, I think a good idea is to not comment to describe your code but again name your code, like don't describe your algorithm if its implementing a known one, instead just make a comment that just states the algorithm being used (if the algorithm cant be extracted to its own method/function and named as such).

Link to comment
Share on other sites

Link to post
Share on other sites

On 2/27/2023 at 11:26 PM, hirushaadi said:
def pythagorean_theorem(a, b):
    """
    Calculates the length of the hypotenuse of a right-angled triangle
    using the Pythagorean theorem.

    Arguments:
    a -- length of the first leg of the triangle
    b -- length of the second leg of the triangle

    Returns:
    c -- length of the hypotenuse of the triangle
    """

    # Calculate the square of the length of each leg
    a_squared = a ** 2
    b_squared = b ** 2

    # Calculate the square of the length of the hypotenuse
    c_squared = a_squared + b_squared

    # Take the square root of c_squared to get the length of the hypotenuse
    c = c_squared ** 0.5

    # Return the length of the hypotenuse
    return c

For example here, I would leave out all the comments besides the docstring. The names already describe what the operations do, and I would rename c to result or something (hypotenuse).

Link to comment
Share on other sites

Link to post
Share on other sites

I'd say you should just to make it easier looking back through your code for yourself or others... There's been times when I've forgotten why I did something so the comments help me remember... Also great if you want to try your code without a line but don't want to delete it incase it's needed... Just comment it out. 

Link to comment
Share on other sites

Link to post
Share on other sites

On 8/20/2022 at 2:45 PM, Tehkast said:

What is a useful comment vs a obvious one as that seems very subjective.

This seems like a subjective thing because there are a lot of people with different answers, but that's because good comments look different in different situations. There's exactly one rule that all good comments follow - good comments save more time in the long run than it takes to write them.

 

On 8/20/2022 at 2:45 PM, Tehkast said:

Is adding comments something really should get into the habit of asap?

If you're asking if you should start adding comments to your code as you're writing it to "practice writing good comments", the answer is probably not, because you won't be able to tell if your comments are any good. When you're writing a piece of code you're in a fundamentally different headspace than someone who's reading it for the first time (or you in the future, having forgotten a lot of the details). You're going to be guessing at which bits that person will find hard to understand, and generally those guesses tend to be bad, and result in comments that aren't actually helpful to anyone else reading the code.

 

The way to get good at writing comments is by reading a lot of code, not writing it. As you're learning to code you're eventually going to have to go back to an old project you don't remember much about, or you'll have to read a new piece of code that you don't understand. When you're doing that at some point you're going to get confused about something. After staring at it a while, and maybe running it with a few print statements added to it to dump out some details that don't make sense to you, you'll have the "aha moment". The code will suddenly make sense. Notice when this happens, and when it does, ask yourself what you could write in a comment that would have made the connection that you missed clear to you on your first reading of the code. You can actually write this out if you think it will be useful in the future, or just do it as a mental exercise. The cool thing about this is that you'll be practicing writing comments that you know, with 100% certainty, are actually useful. If you do this enough you'll find that you have a new "sense" when you're writing code about which parts need comments to make them more clear to someone else, because you've actually been that person before and you've practiced writing actually good comments.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×