Python Quirks: Comments

Philip Trauner
Jul 12, 2017 · 2 min read
Totally valid Python program.

Only one of these “comments” is a real one.
Well, technically speaking all of them are comments, the real difference between them is speed and functionality.

Let’s generate some code to find out what the actual differences between them are.

Executing speed comparison (real comments vs. fake comments).
Real comments took: 0.08859992027282715
Fake comments took: 1.4969751834869385

The “#” comment variant is clearly favourable over the isolated string literal one in this completely unrealistic scenario, so if you ever wanted to include 500000 comments in your code, they are clearly the way to go.

But what’s actually happening here, and because this is Python, can we somehow abuse this behaviour? Let’s examine the AST of our two automatically generated programs to find out.

Syntax tree for real comments


Syntax tree for fake comments


Real comments are simply left out of the final Python AST, just as one would expect. That’s exactly where the speed difference is taking place, string literals still need to be evaluated on program runtime and you should never abuse them for comments. But that doesn’t mean that they are useless.

“No, I’m __doc__!” (””” style docstrings are the prefered in the spec)

Citing PEP-0257:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

Python not only supports isolated strings literals, it essentially supports isolated anything. What’s interesting here is, that all statements are evaluated. In combination with properties this behaviour allows for some very “Ruby-esque” code.

“Ruby-esque” lazy loading

In conclusion: Don’t abuse the language (well, a little can’t hurt, right?)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store