A library that modifies python source code to conform to pep8.

Overview

Pep8ify: Clean your code with ease

https://secure.travis-ci.org/spulec/pep8ify.png?branch=master

Pep8ify is a library that modifies python source code to conform to pep8.

Installation

This library currently works with python 2.7, 3.2, and 3.3.

To install pep8ify, simply:

$ pip install pep8ify

Usage

To print a diff of changes that pep8ify will make against a particular source file or directory:

$ pep8ify source_folder

To have those changes written to the files:

$ pep8ify -w source_folder

By default, this will create backup files for each file that will be changed. You can add the -n option to not create the backups. Please do not do this if you are not using a version control system. Although this code is well-tested, there are most likely bugs still.

For more options about running particular fixers, read the lib2to3 documentation. This library is built on top of that one.

Fixes

A list of the available fixers can be found with the following:

$ pep8ify -l
Available transformations for the -f/--fix option:
blank_lines
compound_statements
extraneous_whitespace
imports_on_separate_lines
indentation
maximum_line_length
missing_newline
missing_whitespace
tabs
trailing_blank_lines
trailing_whitespace
whitespace_around_operator
whitespace_before_inline_comment
whitespace_before_parameters

All of these are set to run by default except for 'maximum_line_length'. To run all fixes including 'maximum_line_length', run:

$ pep8ify -f all -f maximum_line_length example.py
Comments
  • pep8ify not running on Python 2.7.3

    pep8ify not running on Python 2.7.3

    I've tried installing pep8ify by PIP, easy_install and by cloning the git repo and using setup.py. Each time I get this error:

    $ pep8ify test2.py Traceback (most recent call last): File "/usr/local/bin/pep8ify", line 9, in load_entry_point('pep8ify==0.0.5', 'console_scripts', 'pep8ify')() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 337, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2279, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 1989, in load entry = import(self.module_name, globals(),globals(), ['name']) File "/usr/local/lib/python2.7/dist-packages/pep8ify-0.0.5-py2.7.egg/pep8ify/pep8ify.py", line 6, in from lib2to3.main import main ImportError: No module named main

    This is running Python 2.7.3 on Ubuntu Pangolin. The library lib2to3 is installed and I can import it from the interactive interpreter.

    opened by snim2 15
  • In line comments should have 2 spaces (not 1)

    In line comments should have 2 spaces (not 1)

    pep8ify makes the following unnecessarily translation:

    • foo # bar
    • foo # bar

    As per PEP8 inline comments should be separated by 2 spaces, not 1, therefore this particular translation should be avoided.

    opened by giampaolo 7
  • AttributeError: 'NoneType' object has no attribute 'prefix'

    AttributeError: 'NoneType' object has no attribute 'prefix'

    Traceback (most recent call last):
      File "/usr/local/bin/pep8ify", line 9, in <module>
        load_entry_point('pep8ify==0.0.12', 'console_scripts', 'pep8ify')()
      File "/usr/local/lib/python2.7/dist-packages/pep8ify/pep8ify.py", line 17, in _main
        raise SystemExit(lib2to3.main.main("pep8ify.fixes"))
      File "/usr/lib/python2.7/lib2to3/main.py", line 260, in main
        options.processes)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 706, in refactor
        items, write, doctests_only)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 299, in refactor
        self.refactor_dir(dir_or_file, write, doctests_only)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 319, in refactor_dir
        self.refactor_file(fullname, write, doctests_only)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 747, in refactor_file
        *args, **kwargs)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 354, in refactor_file
        tree = self.refactor_string(input, filename)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 386, in refactor_string
        self.refactor_tree(tree, name)
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 426, in refactor_tree
        self.traverse_by(self.bmi_post_order_heads, tree.post_order())
      File "/usr/lib/python2.7/lib2to3/refactor.py", line 502, in traverse_by
        new = fixer.transform(node, results)
      File "/usr/local/lib/python2.7/dist-packages/pep8ify/fixes/fix_missing_whitespace.py", line 31, in transform
        new_prefix = " %s" % next_sibling.prefix.lstrip(' \t')
    AttributeError: 'NoneType' object has no attribute 'prefix'
    
    opened by giampaolo 3
  • Clean-up and enhancements to indent/dedent and some fixes.

    Clean-up and enhancements to indent/dedent and some fixes.

    This is a punch of changes I've done when pep8ifying shinken (see this pull-request), but never created a pull-request for.

    I rebased the changes on current master.

    opened by htgoebel 3
  • pep8ify crashes on simple input

    pep8ify crashes on simple input

    Here's the code:

    # Copyright 2013 Donald Stufft
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    # http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    from __future__ import absolute_import, division, print_function
    from __future__ import unicode_literals
    
    import psycopg2cffi.compat
    
    from warehouse.__about__ import (
        __title__, __summary__, __uri__, __version__, __author__, __email__,
        __license__, __copyright__, __build__,
    )
    
    __all__ = [
        "__title__", "__summary__", "__uri__", "__version__", "__author__",
        "__email__", "__license__", "__copyright__", "__build__",
    ]
    
    
    psycopg2cffi.compat.register()
    

    And the traceback:

    $ pep8ify warehouse/__init__.py
    RefactoringTool: Skipping implicit fixer: maximum_line_length
    Traceback (most recent call last):
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/bin/pep8ify", line 9, in <module>
        load_entry_point('pep8ify==0.0.10', 'console_scripts', 'pep8ify')()
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/pep8ify.py", line 12, in _main
        sys.exit(main("pep8ify.fixes"))
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/main.py", line 260, in main
        options.processes)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 706, in refactor
        items, write, doctests_only)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 301, in refactor
        self.refactor_file(dir_or_file, write, doctests_only)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 747, in refactor_file
        *args, **kwargs)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 354, in refactor_file
        tree = self.refactor_string(input, filename)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 386, in refactor_string
        self.refactor_tree(tree, name)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 426, in refactor_tree
        self.traverse_by(self.bmi_post_order_heads, tree.post_order())
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib2to3/refactor.py", line 500, in traverse_by
        results = fixer.match(node)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 36, in match
        prev_node = get_previous_node(node)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 12, in get_previous_node
        return get_previous_node(node.parent)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 12, in get_previous_node
        return get_previous_node(node.parent)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 12, in get_previous_node
        return get_previous_node(node.parent)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 12, in get_previous_node
        return get_previous_node(node.parent)
      File "/Users/alex_gaynor/.virtualenvs/tempenv-6c9a3044561e1/lib/python2.7/site-packages/pep8ify/fixes/fix_whitespace_before_inline_comment.py", line 10, in get_previous_node
        if node.prev_sibling:
    AttributeError: 'NoneType' object has no attribute 'prev_sibling'
    
    opened by alex 2
  • Pep8ify wants to remove a space before \

    Pep8ify wants to remove a space before \

    I dislike line continuations with \ as much as the next guy, but pep8ify seems to be proposing an unwarranted change to my codebase:

    foo = \
        'some long stuff'
    

    is being corrected to

    foo =\
        'some long stuff'
    

    Which looks weird to my eye. It feels like pep8ify should leave those lines alone.

    opened by PaulMcMillan 2
  • pep8ify indents top level comments

    pep8ify indents top level comments

    I don't believe it should do so, the following code is perfectly fine:

    import foo
    
    # a comment
    
    foo.bar()
    

    but pep8ify emits the following diff:

    --- t.py    (original)
    +++ t.py    (refactored)
    @@ -1,5 +1,4 @@
     import foo
    -
    -# a comment
    +  # a comment
    
     foo.bar()
    
    opened by alex 1
  • ImportError: cannot import name find_indentation

    ImportError: cannot import name find_indentation

    with python2.6, pep8ify raises ImportError as following:

    Traceback (most recent call last):
      File "bin/pep8ify", line 14, in <module>
        pep8ify.pep8ify._main()
      File "/home/mete0r/prj/pyhwp/eggs/pep8ify-0.0.5-py2.6.egg/pep8ify/pep8ify.py", line 12, in _main
        sys.exit(main("pep8ify.fixes"))
      File "/usr/lib/python2.6/lib2to3/main.py", line 156, in main
        options.nobackups, not options.no_diffs)
      File "/usr/lib/python2.6/lib2to3/main.py", line 32, in __init__
        super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
      File "/usr/lib/python2.6/lib2to3/refactor.py", line 606, in __init__
        super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
      File "/usr/lib/python2.6/lib2to3/refactor.py", line 200, in __init__
        self.pre_order, self.post_order = self.get_fixers()
      File "/usr/lib/python2.6/lib2to3/refactor.py", line 218, in get_fixers
        mod = __import__(fix_mod_path, {}, {}, ["*"])
      File "/home/mete0r/prj/pyhwp/eggs/pep8ify-0.0.5-py2.6.egg/pep8ify/fixes/fix_blank_lines.py", line 2, in <module>
        from lib2to3.fixer_util import find_indentation
    ImportError: cannot import name find_indentation
    

    It seems not clear that whether this is a known limitation or unintended error.

    opened by mete0r 1
  • Merge with autopep8?

    Merge with autopep8?

    Just curious if you've seen autopep8. Wondering if you guys should work together if there are no philosophical differences. If there are philosophical differences, it would be nice to document what's different about this one.

    opened by msabramo 1
  • Correctly handle list copies

    Correctly handle list copies

    pep8ify is inserting an extra line when I do in-place list copies with the foo[:] idiom:

    -        return self.prop[:]
    +        return self.prop[:
    +            ]
    

    This doesn't seem right...

    opened by PaulMcMillan 0
  • blank_lines inserts all newlines before final inline comments

    blank_lines inserts all newlines before final inline comments

    I’m not entirely sure if this is a bug, but I don’t think this yields compliant code?

    Versions

    pep8ify/0.0.13 on Python/2.7.11

    $ pep8ify -f blank_lines test.py
    

    Input

    class Foo:
        def __init__(self):
            bar = 13
        def baz(self):
            pass
    class Bar:
        def __init__(self):
            bar = 13  # comment
        def baz(self):
            pass  # comment
    class Baz:
        pass
    

    Expected

    --- test.py     (original)
    +++ test.py     (refactored)
    @@ -1,12 +1,18 @@
     class Foo:
         def __init__(self):
             bar = 13
    +
         def baz(self):
             pass
    +
    +
     class Bar:
         def __init__(self):
             bar = 13  # comment
    +
         def baz(self):
             pass  # comment
    +
    +
     class Baz:
         pass
    

    Actual

    % pep8ify -f blank_lines pep8.py
    RefactoringTool: Refactored pep8.py
    --- test.py     (original)
    +++ test.py     (refactored)
    @@ -1,12 +1,18 @@
     class Foo:
         def __init__(self):
             bar = 13
    +
         def baz(self):
             pass
    +
    +
     class Bar:
         def __init__(self):
    -        bar = 13  # comment
    +        bar = 13
    +  # comment
         def baz(self):
    -        pass  # comment
    +        pass
    +
    +  # comment
     class Baz:
         pass
    RefactoringTool: Files that need to be modified:
    RefactoringTool: pep8.py
    
    opened by delan 1
  • Docstrings should be indented at more than just the first line

    Docstrings should be indented at more than just the first line

    See https://gist.github.com/dhermes/85c3a3a464d2cff312ea for a (super hacky) way to make this work.

    Currently, pep8ify takes

    def hello_func(name):
      """Prints hello with the name.
    
      Args:
        name: String, to print.
      """
      print 'Hello %s, nice to meet you.' % (name,)
    

    and turns it into

    def hello_func(name):
        """Prints hello with the name.
    
      Args:
        name: String, to print.
      """
        print 'Hello %s, nice to meet you.' % (name, )
    

    Running indent_docstrings.py on it gives the desired:

    def hello_func(name):
        """Prints hello with the name.
    
        Args:
          name: String, to print.
        """
        print 'Hello %s, nice to meet you.' % (name, )
    
    opened by dhermes 3
  • Don't insert space after comma for singleton tuples

    Don't insert space after comma for singleton tuples

    Currently pep8ify seems to insert a blank between the comma and the closing bracket of a singleton tuple. I consider this an error. In contradiction to what was written in issue #8, there is a difference between singleton tuples and singleton lists :

    >>> tup = (1,)
    >>> tup
    (1,)
    >>> liz = [1,]
    >>> liz
    [1]
    

    IMO, since the string representation of singleton tuples includes no space before the closing bracket, pep8ify should not insert one. The rule to avoid blanks inside brackets beats the rule to insert a space after commas in this special case.

    opened by tobiasherp 0
  • --help implies user should invoke 2to3, not pep8ify

    --help implies user should invoke 2to3, not pep8ify

    I just installed pep8ify today and found it very useful; thank you!

    When I look for help at the command line:

    $ pep8ify -h Usage: 2to3 [options] file|dir ...

    I have searched around in the repo and cannot figure out where the help message is being generated (so I can give you a pull request to change '2to3' to 'pep8ify'). Help?

    opened by brainwane 2
  • Fix maximum_line_length should be able to break on a long string

    Fix maximum_line_length should be able to break on a long string

    ie

    text = "Imagine this is a string that goes over 80 chars"
    

    to

    text = "Imagine this is a string that"
        " goes over 80 chars"
    
    enhancement 
    opened by spulec 0
Owner
Steve Pulec
Steve Pulec
Simple, hassle-free, dependency-free, AST based source code refactoring toolkit.

refactor is an end-to-end refactoring framework that is built on top of the 'simple but effective refactorings' assumption. It is much easier to write a simple script with it rather than trying to figure out what sort of a regex you need in order to replace a pattern (if it is even matchable with regexes).

Batuhan Taskaya 385 Jan 6, 2023
Code generation and code search for Python and Javascript.

Codeon Code generation and code search for Python and Javascript. Similar to GitHub Copilot with one major difference: Code search is leveraged to mak

null 51 Dec 8, 2022
IDE allow you to refactor code, Baron allows you to write refactoring code.

Introduction Baron is a Full Syntax Tree (FST) library for Python. By opposition to an AST which drops some syntax information in the process of its c

Python Code Quality Authority 278 Dec 29, 2022
Awesome autocompletion, static analysis and refactoring library for python

Jedi - an awesome autocompletion, static analysis and refactoring library for Python Jedi is a static analysis tool for Python that is typically used

Dave Halter 5.3k Dec 29, 2022
a python refactoring library

rope, a python refactoring library ... Overview Rope is a python refactoring library. Notes Nick Smith <[email protected]> takes over maintaining rope

null 1.5k Dec 30, 2022
Find dead Python code

Vulture - Find dead code Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you r

Jendrik Seipp 2.4k Dec 27, 2022
Safe code refactoring for modern Python.

Safe code refactoring for modern Python projects. Overview Bowler is a refactoring tool for manipulating Python at the syntax tree level. It enables s

Facebook Incubator 1.4k Jan 4, 2023
Removes commented-out code from Python files

eradicate eradicate removes commented-out code from Python files. Introduction With modern revision control available, there is no reason to save comm

Steven Myint 146 Dec 13, 2022
Turn your C++/Java code into a Python-like format for extra style points and to make everyone hates you

Turn your C++/Java code into a Python-like format for extra style points and to make everyone hates you

Tô Đức (Watson) 4 Feb 7, 2022
A simple Python bytecode framework in pure Python

A simple Python bytecode framework in pure Python

null 3 Jan 23, 2022
A system for Python that generates static type annotations by collecting runtime types

MonkeyType MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type

Instagram 4.1k Dec 28, 2022
Tool for translation type comments to type annotations in Python

com2ann Tool for translation of type comments to type annotations in Python. The tool requires Python 3.8 to run. But the supported target code versio

Ivan Levkivskyi 123 Nov 12, 2022
Bottom-up approach to refactoring in python

Introduction RedBaron is a python library and tool powerful enough to be used into IPython solely that intent to make the process of writing code that

Python Code Quality Authority 653 Dec 30, 2022
AST based refactoring tool for Python.

breakfast AST based refactoring tool. (Very early days, not usable yet.) Why 'breakfast'? I don't know about the most important, but it's a good meal.

eric casteleijn 0 Feb 22, 2022
Refactoring Python Applications for Simplicity

Python Refactoring Refactoring Python Applications for Simplicity. You can open and read project files or use this summary ?? Concatenate String my_st

Mohammad Dori 3 Jul 15, 2022
Leap is an experimental package written to enable the utilization of C-like goto statements in Python functions

Leap is an experimental package written to enable the utilization of C-like goto statements in Python functions

null 6 Dec 26, 2022
FindFunc is an IDA PRO plugin to find code functions that contain a certain assembly or byte pattern, reference a certain name or string, or conform to various other constraints.

FindFunc: Advanced Filtering/Finding of Functions in IDA Pro FindFunc is an IDA Pro plugin to find code functions that contain a certain assembly or b

null 213 Dec 17, 2022
Borderless-Window-Utility - Modifies window style to force most applications into a borderless windowed mode

Borderless-Window-Utility Modifies window style to force most applications into

null 8 Oct 22, 2022
SCodeScanner stands for Source Code scanner where the user can scans the source code for finding the Critical Vulnerabilities.

The SCodeScanner stands for Source Code Scanner, where you can scan your source code files like PHP and get identify the vulnerabilities inside it. The tool can use by Pentester, Developer to quickly identify the weakness.

null 136 Dec 13, 2022