Classes as namespaces?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 26 20:03:30 EDT 2010


On Fri, 26 Mar 2010 14:49:02 +0000, kj wrote:

> What's the word on using "classes as namespaces"? 


>>> import this
[...]
Namespaces are one honking great idea -- let's do more of those!




> [*] My own subjective dislike for the widespread practice of using
> triple quotes to comment out code is formally similar to this one ("the
> 'intended use' for triple-quoting is not to comment out code", etc.). 

On the contrary. CPython deliberately strips bare strings (whether triple 
quoted or not) out during compilation. This isn't an accident, it is 
deliberate.


>>> code = """
... x = 1
... y = 2
... # comment
... "a string"
... z = 4
... """
>>> o = compile(code, '', 'exec')
>>> dis.dis(o)
  2           0 LOAD_CONST               0 (1)
              3 STORE_NAME               0 (x)

  3           6 LOAD_CONST               1 (2)
              9 STORE_NAME               1 (y)

  6          12 LOAD_CONST               2 (4)
             15 STORE_NAME               2 (z)
             18 LOAD_CONST               3 (None)
             21 RETURN_VALUE


Why should you not do this? First, it is implementation-specific: other 
Pythons may not behave the same. Potentially they may compile in the 
(potentially large) string, push it on the stack, then immediately pop it 
off again. Older versions of CPython used to do that for non-strings.


Secondly, and FAR more importantly, leaving large amounts of commented 
out code in your source is a TERRIBLE idea. Yes, sure, it's tempting to 
do, especially for quick and dirty scripts. Resist the temptation. Learn 
how to use a proper code repository. Don't leave the detritus of ancient 
unused code in your source files -- it confuses the reader, makes 
searching harder, slows down parsing, and (trust me) you will never need 
to read the old code again. It just gets in the way.

Of course, like everything, this needs to be considered in context. You 
might leave commented-out code like this:

# DON'T DO THIS:
# s = spam(s, s*2)
# It doesn't work. See bug #12345 in the tracker. Instead do this:
s = spam(s*2, s)



-- 
Steven



More information about the Python-list mailing list