Python Quirks: Comments

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

Module

Syntax tree for fake comments

Module
Expr
Str
Expr
Str
Expr
Str
Expr
Str
Expr
Str
...

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?)