Comments

Tim Peters tim.one at comcast.net
Wed May 8 15:46:11 EDT 2002


[Sean 'Shaleh' Perry]
> Sure, but comments are basically free whereas the above creates
> an anonmymous string which has to be garbage collected.

Perhaps surprisingly, it does not.  A little-known optimization (one of the
few the compiler does) is that Python throws away all string literal
statements, except for those in docstring positions.  It does this whether
or not -O is enabled.

So

def f():
    "This is saved -- it's a docstring"

    """Except for its effect on line numbers in tracebacks, this
       string doesn't exist -- the compiler throws it away.
    """

    return 3

Cute:  A few years ago there was a debate about whether Python should
*start* doing this optimization.  Guido eventually decided that it should.
I then had the joy of pointing out that it already did <wink>.

a-time-machine-in-every-pot-ly y'rs  - tim






More information about the Python-list mailing list