Monday 16 May 2016

Indentation problem in Python

Solving indentation problem in Python



Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (:) and the indentation of the code itself.
So indentation plays a major part in python coding.

But how to check indentation in python?

There is a library in python called tabnanny, that provides user to check indentation of your code both at file and directory level.

to check indentation of any python file:-


open python console


>>> import tabnanny;

>>> tabnanny.check("main.py");
'main.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 9)

tabnanny.check(file_or_dir)
If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files along the way. Iffile_or_dir is an ordinary Python source file, it is checked for whitespace related problems. The diagnostic messages are written to standard output using the print statement.
So check method of tabnanny checks for indentation on file level and also on directory level by scanning .py files.
You can also check for indentation from terminal without opening python console.

$ python -m tabnanny main.py 

'main.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 9)


For more info about it take a look into tabnanny documentation and examples(https://docs.python.org/2/library/tabnanny.html )

No comments:

Post a Comment