Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to fix PEP-8 issues with pydev?

Tags:

python

pydev

I want to know if there is any way to fix all the PEP-8 issues automatically with a keyboard shortcut in eclipse-pydev. Googling did not get me anywhere.

Since Pydev can detect the PEP-8 issues, should it not be possible to fix them automatically?

like image 695
Ranjith Ramachandra Avatar asked Jun 15 '12 06:06

Ranjith Ramachandra


People also ask

What is pep8 and why it is important?

PEP 8 is a document that provides various guidelines to write the readable in Python. PEP 8 describes how the developer can write beautiful code. It was officially written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The main aim of PEP is to enhance the readability and consistency of code.

Which variable name is best according to the Python pep8 guidelines?

See Python PEP 8: Function and Variable Names: Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names.


2 Answers

You can manually activate the PyDev code-formatter with Ctrl+Shift+F (preferences at: Window > Preferences > PyDev > Editor > Code Style > Code Formatter -- note that you can configure it to run automatically under Window > Preferences > PyDev > Editor > Save Actions).

Note that the internal PyDev code-formatter is pretty conservative and won't do all transformations required for 100% compatible PEP8 code (although it handles the more common cases), so, if it's not enough for your needs, you have some options:

  1. You can use autopep8.py or black which are also integrated into PyDev by default in the latest version (Enabled via Window > Preferences > PyDev > Editor > Code Style > Code Formatter > Formatter Style? and then select autopep8 or black).

  2. You can take a look at PythonTidy (external tool)... it's possible to use it as defined in: http://bear330.wordpress.com/2007/10/30/using-pythontidy-in-pydev-as-code-formatter/

like image 147
Fabio Zadrozny Avatar answered Sep 21 '22 16:09

Fabio Zadrozny


I have made a script make it possible to use autopep8 in pydev as code formatter, and it can be customized to satisfy the coding standard in your team.

If you want to use it, save this code somewhere as pyedit_autopep8.py (pyedit_XXXX.py is required). You also have to install the python packages pep8 and autopep8.

Next, go to eclipse pydev preferences page (at: window > preferences > pydev > scripting pydev) to specify the script location:

Now, in order to invoke autopep8 you can simply press Ctrl+Shift+F while editing python code in eclipse. Format selected text is also supported!

"""
By Per A. Brodtkorb
based on pyedit_pythontidy.py by Bear Huang (http://bear330.wordpress.com/).

This code is public domain.
"""

import tempfile
import os

if False:
    from org.python.pydev.editor import PyEdit  # @UnresolvedImport
    cmd = 'command string'
    editor = PyEdit

assert cmd is not None
assert editor is not None

if cmd == 'onCreateActions':
    from org.python.pydev.editor.actions import PyAction
    from org.python.pydev.core.docutils import PySelection
    from java.lang import Runnable
    from org.eclipse.swt.widgets import Display
    from java.io import FileWriter
    import java.lang.Exception

    FORMAT_ACTION_DEFINITION_ID = "org.python.pydev.editor.actions.pyFormatStd"
    FORMAT_ACTION_ID = "org.python.pydev.editor.actions.navigation.pyFormatStd"

    class Autopep8Action(PyAction):
        def _autopep8(self, text):
            tmp_full_file_name = tempfile.mktemp()
            f1 = FileWriter(tmp_full_file_name)
            f1.write(text)
            f1.close()
            os.system('autopep8-script.py -i "%s"' % (tmp_full_file_name))
            f2 = open(tmp_full_file_name, "r")
            tidy_text = f2.read()
            f2.close()
            os.remove(tmp_full_file_name)
            return tidy_text

        def _get_text(self, selection):
            text = selection.getSelectedText()
            format_all = len(text) == 0
            if format_all:
                print "Autopep8: format all."
                text = selection.getDoc().get()
                text_offset = 0
            else:
                print "Autopep8: Format selected."
                text_offset = selection.getAbsoluteCursorOffset()
            return text, text_offset

        def run(self):
            try:
                selection = PySelection(editor)

                text, text_offset = self._get_text(selection)
                tidy_text = self._autopep8(text)

                if len(text)==len(tidy_text):
                    print "Autopep8: Nothing todo!"
                else:
                    doc = selection.getDoc()
                    doc.replace(text_offset, len(text), tidy_text)

            except java.lang.Exception, e:
                self.beep(e)

    def bindInInterface():
        act = Autopep8Action()
        act.setActionDefinitionId(FORMAT_ACTION_DEFINITION_ID)
        act.setId(FORMAT_ACTION_ID)
        try:
            editor.setAction(FORMAT_ACTION_ID, act)
        except:
            pass

    class RunInUi(Runnable):

        '''Helper class that implements a Runnable (just so that we
        can pass it to the Java side). It simply calls some callable.
        '''

        def __init__(self, c):
            self.callable = c

        def run(self):
            self.callable()

    def runInUi(callable):
        '''
        @param callable: the callable that will be run in the UI
        '''
        Display.getDefault().asyncExec(RunInUi(callable))

    runInUi(bindInInterface)
like image 34
user2549818 Avatar answered Sep 23 '22 16:09

user2549818