Python Tidy Code - python

I edit all my Python files on a remote Centos server using nano. This seems to work well. Occasionally I need to make a small change that changes the indention over the entire file. Is there an easy way to convert all the one space indents to 4 space etc? I have looked at PythonTidy.py but it seems to change too many things.

Not sure if you would consider switching editors. You can customize VIM so it handles auto indentation and easily set tabs to spaces vice versa using the vimrc file. Vim also has a convenient fix indentation command for your issue.

In you're favorite text editor, use search and replace. Find all the instances of
"\n [^-\s]"
and replace them with
"\n "
As long as it takes the newline and regex as expected, it'll indent all the newlines followed by a space followed by a not whitespace (meaning, it won't change 4 spaces into 7 spaces).

I found this:
How to fix python indentation
Installed python-tools then used reindent.py. Worked absolutely perfect.
Thanks.

Related

How to manage 'inconsistent use of tabs and spaces in indentation' across editors

I've been working with python for a while, and understand how to use tabs correctly, but recently in a project I have started working across Jupyter notebooks and Sublime. When I copy and paste code over, the indentation gets completely messed up. Usually it goes from tabs to 4 spaces and it doesn't like that so I have to manually change every line. It happens on occasion when I copy from one python file to another in just Sublime as well.
Is there some sort of general way, or just setting within those applications, that can prevent this?
Jupyter Notebooks indent with 4 spaces by default. Not sure where you'd be getting tabs unless you originally copy-pasted tabs.
If you want to keep the tabs in SublimeText, select a Python file, go to "Preferences" --> "Settings - Syntax Specific" and add the line:
"translate_tabs_to_spaces": false
Although, if your sources were already mixed (some cells in jupyter use tabs, some use spaces) then it's better to standardise on paste in sublime, and use:
"translate_tabs_to_spaces": true
Also, when you're pasting in SublimeText, instead of just Paste with Ctrl+V, use Paste & Indent: Ctrl+Shift+V
Btw, Python3 recommends 4 spaces by default, almost as a standard. So maybe set that in your editor. Most of them have settings for "Tabs & Indents" somewhere with code formatting.

textmate >> vim for python - teething troubles: especially indenting

I'm (attempting) to move from textmate to vim [macvim to be exact] as my primary editor. I have already installed snipmate - wondering if there are other plugins you would suggest I install?
In particular I seem to be having a lot of trouble with indenting (<< seems to really do some very strange/unpredictable things), and I can't seem to find a solution for this - are there plugins I need for this to work properly?
Thanks!
For source code,
:h =
In a nutshell, in normal mode inside a block you wish to work with:
=a{ to re-indent a block. =a} and =aB work as well.
=2a{ to re-indent this block and its outer block.
If you happen to stand on a brace then =% will re-indent up to the matching brace.
>a{ to increase the indent of this block.
<a{ to decrease the indent of this block.
. repeats the last command, so <a{. decreases the indent of this block twice.
Make sure you have filetype set so Vim recognizes the filetype. Indenting is a function of the file type, after all.
For text,
:h gq
gq{ will format this paragraph.
gq( will format this sentence.
gqgq will format this line.
gggqG will format the entire document.
Set the filetype setting in your vimrc file
filetype plugin indent on
That should enable filetype plugins and automatic indentation
I am not sure what you need exactly as I have not used textmate. But I do use these Plugins for VIM. They have helped me a lot.

Which is the closest Python equivalent to Perl::Tidy?

Coming from Perl I've been used to hitting C-c t to reformat my code according to pre-defined Perl::Tidy rules. Now, with Python I'm astonished to learn that there is nothing that even remotely resembles the power of Perl::Tidy. PythonTidy 1.20 looks almost appropriate, but barfed at first mis-aligned line ("unexpected indent").
In particular, I'm looking for the following:
Put PEP-8 into use as far as possible (the following items are essentially derivations of this one)
Convert indentation tabs to spaces
Remove trailing spaces
Break up code according to the predefined line-length as far as it goes (Eclipse-style string splitting and splitting method chains)
Normalize whitespace around
(bonus feature, optional) Re-format code including indentation.
Right now, I'm going throught someone else's code and correct everything pep8 and pyflakes tell me, which is mostly "remove trailing space" and "insert additional blank line". While I know that re-indentation is not trivial in Python (even though it should be possible just by going through the code and remembering the indentation), other features seem easy enough that I can't believe nobody has implemented this before.
Any recommendations?
Update: I'm going to take a deeper look at PythonTidy, since it seems to go into the right direction. Maybe I can find out why it barfs at me.
There is a reindent.py script distributed with python in the scripts directory.
untabify.py (Tools/scripts/untabify.py from the root directory of a Python source distribution) should fix the tabs, which may be what's stopping Python Tidy from doing the rest of the work.
Have you tried creating a wrapper around pythontidy? There's one for the sublime editor here.
Also, does pythontidy break up long lines properly for you? When I have a long line that ends in a tuple, it creates a new line for every entry in the tuple, instead of using Python's implied line continuation inside parentheses, brackets and braces as suggested by PEP-8.
I have used autopep8 for this purpose and found it handy.

Enforce "spaces" or "tabs" only in python files?

In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ?
Well, perhaps "enforce" is too strong, more like a "recommendation".
I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I am searching something to do that at the editor level, like it exists for the charset.
Edit : Ok, my question wasn't clear, I am asking this because I keep receiving corrections and patches in any mix of tab/space you can imagine. I am using Mercurial as a DVCS, perhaps something exists at this level ?
Tim Peters has written a nifty script called reindent.py which converts .py files to use 4-space indents and no tabs. It is available here, but check your distribution first -- it may have come bundled in an Examples or Tools directory. (On the latest LTS Ubuntu, it is provided by the python2.7-examples package.)
If you can set up a Mercurial hook you should be able to run all files through reindent.py.
By the way, if you are using unix, then your system may also have the expand (and unexpand) command, which convert all tabs to spaces (and spaces to tabs). However, in this case, I think reindent.py is the right tool.
Look at the tabnanny module: — Detection of ambiguous indentation.
This is something your editor should do for you. Most editors (try Notepad++ for example, it's free) will let you set whether hitting tab enters a tab character or a number of spaces. I'd recommend using two spaces instead of tab in all files (I find 4 is too much). Using spaces instead of tabs is better as it means that you can indent stuff using both the space & tab keys without worrying about messing up your files.
If you have files that have a mix it isn't hard to write your own script to convert tabs to spaces
As explicited in PEP 8, never mix tabs and space. However, a file with both may just run...
As it says there:
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
the solution is therefore to use as a default:
python -t my_mixed_code.py
To answer at the editor level, this depends on the editor, please specify!

Python tool to balance parentheses, quotes, and brackets

Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.)
I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement" and start swearing, because it means that somewhere in about 200 lines of code I forgot a closing parenthesis or quote and IDLE can't tell me where. This seems like a fairly straightforward thing, I just don't really have the time or headspace to work it out myself right now.
Much thanks
I use Eclipse with PyDev. It's very good for this sort of thing, and lots more.
emacs will automatically highlight matching pairs of parentheses/brackets/quotes/etc. as you type them, and it will inform you immediately if you mismatch them (e.g. if you type a [ followed by a )). I'm sure vim also does this, but since I don't use vim, I can't say with certainty.
PyDev is the best IDE to develop in Python. Has this feature and a lot of more.
If you use the vim text editor, there is a syntax highlighter for Python that might be of some help. Vim's python indenting rules also line up a new line with an unmatched open parenthesis from the previous line. That's been my visual cue that something is unbalanced.

Categories

Resources