Using the Python Interpreter as a Reference

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 1 19:43:02 EST 2011


On Thu, 01 Dec 2011 10:03:53 -0800, DevPlayer wrote:

[...]
> Well, that may be a little hyperbolic. But with 2 spaces you can
> encourage coders to get very deep, indentially, and still fit 80 chars.

Why would you want to encourage coders to write deeply indented code?

In my opinion, if your code is indented four or more levels, you should 
start to think about refactorising your code; if you reach six levels, 
your code is probably a mess.

class K:
    def spam():
        if x:
            for a in b:
                # This is about as deep as comfortable
                while y:
                    # Code is starting to smell
                    try:
                        # Code smell is now beginning to reek
                        with z as c:
                            # And now more of a stench
                            try:
                                # A burning, painful stench
                                if d:
                                    # Help! I can't breathe!!!
                                    for e in f:
                                        # WTF are you thinking?
                                        try:
                                            # DIE YOU M***********ER!!!
                                            while g:
                                                # gibbers quietly
                                                ...


The beauty of languages like Python where indentation is significant is 
that you can't hide from the ugliness of this code. 

class K: {
  # Code looks okay to a casual glance.
  def spam():{
   if x: { for a in b:{
     while y:{ try:{ with z as c:{
       try:{ if d:{ for e in f:{ try:{
         while g:{ ... }}}}
       }}}}
     }}}}

Deeply indented code *is* painful, it should *look* painful.


-- 
Steven



More information about the Python-list mailing list