Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I beautify (auto-format) a piece of code in Spyder IDE

Tags:

python

ide

spyder

How can I select a piece of code and apply auto-format, aka beautification to it?

I especially mean correctly indenting lists broken into several lines, parentheses and square brackets.

Auto-indent does nothing.

like image 747
João M. S. Silva Avatar asked May 31 '16 10:05

João M. S. Silva


People also ask

How do you format a Python script?

You can set your formatting options through the menus Tools > Options > Text Editor > Python > Formatting and its nested tabs. Formatting options by default are set to match a superset of the PEP 8 style guide.

Does Spyder have auto indentation?

Smart auto-indentation based on code structure.

What does #%% do in Spyder?

A cell is created with a comment line that starts with #%% . Adding these to your script allows you to use the Outline Viewer to quickly navigate around your code.

How do I correct a Spyder indentation?

In Spyder v5. 3.3, Also, go to Source --> Fix Indentation. That worked for me.

How do you use Spyder autopep8?

Press Shift+F8 (default) to run autopep8 on the current file or go to Source > Run autopep8 code autoformatting. If some text is selected, autopep8 will run on this text only. Informations about the execution will be displayed in the statusbar.


2 Answers

Nowadays (or at least in Spyder v5), Spyder includes autopep8 directly in the GUI and has an option of automatic formatting (as requested in the original question).

Simply go to Tools > Preferences then choose Completion and linting > Code style and formatting. There, toggle on Enable code style linting and Autoformat files on save.

Now when you save your file, Spyder will beautify your code, when it can infer what to do. This should include adding missing whitespaces after commas or around operators, removing whitespaces in empty lines or missing new lines to separate functions, just to name a few.

like image 142
VicN Avatar answered Nov 15 '22 05:11

VicN


One possible solution is to use this plugin: autopep8 for Spyder

Although since Python is a language where code functionality depends on the amount of whitespace, beautification tools can never really format the code in an unified way.

Unfortunately, autopep8 does not solve code formatting conventions that are violated (as indicated by Pylint).

like image 42
João M. S. Silva Avatar answered Nov 15 '22 05:11

João M. S. Silva