why no block comments in Python?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Mar 10 18:23:56 EST 2006


On Thu, 09 Mar 2006 18:02:27 -0600, Terry Hancock wrote:

> On 9 Mar 2006 07:21:00 -0800
> "msoulier" <msoulier at gmail.com> wrote:
>> > (and if you don't, you can quickly comment out regions
>> > by putting them inside a triple-quoted string.)
>> 
>> Although that will use up memory, as opposed to a comment.
> 
> Not really. Unless it is the first string in the block
> (class, function, module), it won't be assigned to anything,
> and will be immediately garbage-collected.
> 
> It may consume space in the pyc file, I'm not sure.

I don't believe this is true. Unassigned strings other than the doc string
are not compiled into the code:

>>> def f(x):
...     "this is a doc string"
...     "but this isn't"
...     return "hello world"
...
>>> dis.dis(f)
  4           0 LOAD_CONST               1 ('hello world')
              3 RETURN_VALUE
              4 LOAD_CONST               2 (None)
              7 RETURN_VALUE


Strangely enough, this is a local optimization that appears to have been
done only for strings: 

>>> def g():
...     45
...     return 55
...
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (45)
              3 POP_TOP
 
  3           4 LOAD_CONST               2 (55)
              7 RETURN_VALUE
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE

So you should feel free to use strings (triple-quoted or otherwise) as
documentation in your functions.

-- 
Steven.




More information about the Python-list mailing list