Tuesday, December 25, 2007

python: code indentation

The most interesting thing in python's syntax is indentation. You can't write non-indented code - interpreter will argue you: you have to indent function's, loop's, condition's etc. bodies. It's a great thing except that the python interpreter doesn't bother how you indent your code. You can indent it with a single space or eight tabs. The thing you have to worry about - to keep one style of indentation in one block(e.g. you can indent function's body with tabs and loop's body inside the function you can indent with spaces for example). Also you may write inline code. So you can write indeed ugly code in python. It seems ugly as for me:

def func():
 for i in xrange(10):
                     if i <= 5: print i + 1
                       print i - 2
So what's the purpose of python's code indentation requirement if you can anyway easily break the code?


Cheba said...

You can mess the formatting but not break the code. =)

Python requires indentation because it doesn't have other block definition structures like {} in C-like languages or begin-end in Pascal/Delphi (Ruby has this too but it's used quiet rarely).

Ni@m said...

The main idea of python's code indention is missed with such indetion rules =/.

If Guido had defined that you have to follow one indention way through the whole script then nobody would have to suffer because of this.

Cheba said...

Who knows?.. Maybe in early versions it was so but he changed in under community pressure. It happens.