Code Blocks and Indentation

Unlike many traditional languages, in Python proper indentation of your code isn't just suggested, it's required. This is the number one complaint people give about using Python. I've personally never understood why. If you're used to indenting your code the way it should be, then this isn't a problem. If you're not, then maybe you should be, so your partners on your next team project aren't yelling at you for having hard to read code. Here is an example from a module I wrote:

#fraction.py

class fraction( object ):
    """
    A class for dealing with fractions
    """
    _VALID_TYPES = ( types.IntType, types.LongType )
    def __init__( self, *arg ):
        """
        Constructor. Takes either 2 ints ( or longs ) or a fraction. Passing the constructor a
        fraction simply makes a copy of the original.
        :Parameters:
            arg : int
                A series of arguments
        """
        self.numerator = arg[ 0 ]
        self.denominator = arg[ 1 ]
        self._reduce( )
    def _reduce( self ):
        numFactors = self._factor( self.numerator )
        denFactors = self._factor( self.denominator )
        i = j = 0
        while ( i < len( numFactors ) ):
            j = 0
            while ( j < len( denFactors ) ):
                if ( numFactors[ i ] == denFactors[ j ] ):
                    self.numerator /= numFactors[ i ]
                    self.denominator /= denFactors[ j ]
                    numFactors.pop( i )
                    denFactors.pop( j )
                    j = 0
                else:
                    j+=1
            i+=1

As you can see, instead of using brackets to enclose code blocks, each block is determined by it's indention level. The amount of indentation doesn't matter as long as the levels are consistent. Although tabs will work, I recommend not using them, as this can cause some problems for cross-platform applications. The defualt used by the Python IDE is 4 spaces when the tab key is pressed.

Powered by Drupal - Design by artinet