GithubHelp home page GithubHelp logo

pycqa / pycodestyle Goto Github PK

View Code? Open in Web Editor NEW
5.0K 116.0 751.0 1.8 MB

Simple Python style checker in one Python file

Home Page: https://pycodestyle.pycqa.org

License: Other

Makefile 0.06% Python 99.94%
python pep8 styleguide style-guide linter-plugin linter-flake8 flake8-plugin

pycodestyle's Introduction

pycodestyle (formerly called pep8) - Python style guide checker

Build status

Documentation Status

Wheel Status

Join the chat at https://gitter.im/PyCQA/pycodestyle

pycodestyle is a tool to check your Python code against some of the style conventions in PEP 8.

Note

This package used to be called pep8 but was renamed to pycodestyle to reduce confusion. Further discussion can be found in the issue where Guido requested this change, or in the lightning talk at PyCon 2016 by @IanLee1521: slides video.

Features

  • Plugin architecture: Adding new checks is easy.
  • Parseable output: Jump to error location in your editor.
  • Small: Just one Python file, requires only stdlib. You can use just the pycodestyle.py file for this purpose.
  • Comes with a comprehensive test suite.

Installation

You can install, upgrade, and uninstall pycodestyle.py with these commands:

$ pip install pycodestyle
$ pip install --upgrade pycodestyle
$ pip uninstall pycodestyle

There's also a package for Debian/Ubuntu, but it's not always the latest version.

Example usage and output

$ pycodestyle --first optparse.py
optparse.py:69:11: E401 multiple imports on one line
optparse.py:77:1: E302 expected 2 blank lines, found 1
optparse.py:88:5: E301 expected 1 blank line, found 0
optparse.py:347:31: E211 whitespace before '('
optparse.py:357:17: E201 whitespace after '{'
optparse.py:472:29: E221 multiple spaces before operator

You can also make pycodestyle.py show the source code for each error, and even the relevant text from PEP 8:

$ pycodestyle --show-source --show-pep8 testing/data/E40.py
testing/data/E40.py:2:10: E401 multiple imports on one line
import os, sys
         ^
    Imports should usually be on separate lines.

    Okay: import os\nimport sys
    E401: import sys, os

Or you can display how often each error was found:

$ pycodestyle --statistics -qq Python-2.5/Lib
232     E201 whitespace after '['
599     E202 whitespace before ')'
631     E203 whitespace before ','
842     E211 whitespace before '('
2531    E221 multiple spaces before operator
4473    E301 expected 1 blank line, found 0
4006    E302 expected 2 blank lines, found 1
165     E303 too many blank lines (4)
325     E401 multiple imports on one line
3615    E501 line too long (82 characters)

pycodestyle's People

Contributors

anntzer avatar asfaltboy avatar asottile avatar cburroughs avatar cdce8p avatar dannysepler avatar daspecster avatar doismellburning avatar emonty avatar ericcousineau-tri avatar florentx avatar gward avatar ianlee1521 avatar ilam avatar jcrocholl avatar jdufresne avatar mjsir911 avatar mtmiller avatar myint avatar pierre-sassoulas avatar pre-commit-ci[bot] avatar rach avatar reinout avatar rettenbs avatar sandsbit avatar scop avatar sigmavirus24 avatar smileychris avatar timleslie avatar yole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pycodestyle's Issues

E221 and E222 not raised

Following cases should trigger PEP8 validation errors

x[0]          = 1
x[1]          = 2
long_variable = 3

x = f(x)          + 1
y = long_variable + 2
z = x[0]          + 3

x[0] =          1
x[1] =          2
long_variable = 3

Add a license

This code can't be used in open source projects if it is not licensed under an open source license. A license file is needed to clarify how the code can legally be used.

Problems with whitespaces E251 and E202

When i check source i got:
pep8.exe --show-source bazar\views.py
bazar\views.py:20:38: E251 no spaces around keyword / parameter equals
p = Category.objects.get(id = categoryId)
^
bazar\views.py:97:42: E202 whitespace before ')'
customData = json.dumps(resp)

But in both cases something is wrong, in first there are spaces, and in second dont.
Its error in checker or its my mistake?

Source in UTF-8 with unix (\n) end of lines.
pep8 v. 0.5.0
python 2.6.1
OS: WinXP

Implement pep8 code checking for only modified code (diffs)

Something that would nice for pep8 to implement would be code checking for diffs, This would allow developers to only check the sections of code that they modified rather then the entire file.

A good example of this is the checkpatch.pl script that is maintained for the linux kernel tree. This script is diff aware so that a user can call it with a diff and it will only analyse the code that has changed as part of this diff.

The idea being that pep8 would be executed from a sandbox, have a diff passed to it, and only check the lines that have been modified in the diff.

--exclude option doesn't work on some cases

Hi,
We've integrated your pep8 module in the unit tests of our Django CMS application.
The module is very convenient but we've found a bug with the --exclude option on the version 0.6.1 of pep8.
It occurs when we try to exclude two dirs which are alphabetically next to each other.
This is because the dirs.remove(subdir) of the input_dir method is modifying the sequence being iterated.
This isn't safe as stated in the Python documentation:
http://docs.python.org/tutorial/controlflow.html#for-statements

This example illustrate the bug, where "dir2" doesn't get ignored like it should:

$ find . -type f
./dir1/invalid.py
./dir2/invalid.py
$ pep8  .
./dir1/invalid.py:1:1: W391 blank line at end of file
./dir1/invalid.py:1:1: W293 blank line contains whitespace
$ pep8 --exclude dir1,dir2 .
./dir2/invalid.py:1:1: W391 blank line at end of file
./dir2/invalid.py:1:1: W293 blank line contains whitespace
$

Making a slice copy of the entire list as suggested in the above documentation works as a patch.

--- pep8.py     2012-01-19 00:23:57.790219545 +0100
+++ pep8.py.new 2012-01-19 00:25:30.094222777 +0100
@@ -1041,7 +1041,7 @@
             message('directory ' + root)
         options.counters['directories'] += 1
         dirs.sort()
-        for subdir in dirs:
+        for subdir in dirs[:]:
             if excluded(subdir):
                 dirs.remove(subdir)
         files.sort()

After applying the patch both dir1 and dir2 get ignored as expected:

$ pep8 --exclude dir1,dir2 .
$

Clarify development situation

I don't know the status of developer permissions in this repository or on PyPI, so I'm not sure how to resolve this issue.

The PyPI page says that the source can be forked on Github at this repository (http://github.com/jcrocholl/pep8/). However, this repository is not the most updated version. It looks like the most up-to-date version is at https://github.com/florentx/pep8. It looks like @florentx is merging pull requests into his version, but not closing issues and pull requests (probably because of permissions).

To resolve this issue I propose one of a few solutions:

  1. @jcrocholl could give @florentx permission to administer this repository (http://github.com/jcrocholl/pep8/)
  2. The repository URL on PyPI could be updated to point to https://github.com/florentx/pep8 and the description at this repository could be updated to note that change
  3. @jcrocholl could merge changes into this repository as @florentx makes them

PEP8 Should Check PEP8 Naming Conventions

It would be very nice if the PEP8 tool could check source files for compliance with the "Naming Conventions" from PEP8. In particular, I would like warnings if I write a method with a name like myCamelCaseMethod where it should be (according to PEP8) my_underscore_method.

"W602 deprecated form of raising exception" with "raise t, v, tb"

I'm not entirely sure this is a bug in pep8, but I can't an alternative way to format the following code:

try:
    foo()
except:
    t, v, tb = sys.exc_info()
    try:
        bar()
    except:
        pass
    raise t, v, tb

In this particular case, bar() could raise an exception I don't care about, so the last raise can't be just "raise" because it might just reraise bar()'s exception and I want the original exception. I did a bunch of searching, but I can't find where "raise t, v, tb" is deprecated, just things like "raise v".

Confirmation on a bug or information on setting me straight would be much appreciated. :)

installation problem

after typing,
[root@xxxxxx-xxxxxx samples]# easy_install pep8
Searching for pep8
Reading http://cheeseshop.python.org/pypi/pep8/
error: Download error: (101, 'Network is unreachable')

it seems a problem of easy_install, because i have the same error when install others like pylint.

but what is wrong? how to solve it? Thanks in advance.

E251 false positive

This is from the copy module.

d[type(None)] = _deepcopy_atomic
copy_example.py:1:14: E251 no spaces around keyword / parameter equals
copy_example.py:1:16: E251 no spaces around keyword / parameter equals

Does not follow symlink

pep8 crash when encounter symlink file.

See:

Traceback (most recent call last):
  File "/usr/local/bin/pep8", line 8, in <module>
    load_entry_point('pep8==0.5.0', 'console_scripts', 'pep8')()
  File "/Library/Python/2.6/site-packages/pep8-0.5.0-py2.6.egg/pep8.py", line 1238, in _main
    input_dir(path)
  File "/Library/Python/2.6/site-packages/pep8-0.5.0-py2.6.egg/pep8.py", line 1005, in input_dir
    input_file(os.path.join(root, filename))
  File "/Library/Python/2.6/site-packages/pep8-0.5.0-py2.6.egg/pep8.py", line 977, in input_file
    errors = Checker(filename).check_all()
  File "/Library/Python/2.6/site-packages/pep8-0.5.0-py2.6.egg/pep8.py", line 772, in __init__
    self.lines = open(filename).readlines()
IOError: [Errno 2] No such file or directory: './scripts/clear-html-cache.py'

Where ./scripts/clear-html-cache.py is a symlink.

rc file

It would be nice to have an rc file to specify regularly used options, etc. (currently using shell command alias).
Thanks.

Deny direct variable type comparison

According to PEP8,

- Object type comparisons should always use isinstance() instead
      of comparing types directly.

        Yes: if isinstance(obj, int):

        No: if type(obj) is type(1):

      When checking if an object is a string, keep in mind that it might be a
      unicode string too! In Python 2.3, str and unicode have a common base
      class, basestring, so you can do:

        if isinstance(obj, basestring):

People, including me, tend to import the types module and do something like "type(XXX) is types.IntType".

Comparing types directly should trigger an error.

E241 is more restrictive than PEP8

I was looking at some Python code and I had a second though about E241.
This check is about "multiple spaces after comma". It is not part of PEP8.

According to PEP 8, we should avoid "More than one space around an assignment (or other) operator to align it with another."
This is enforced by E221,E222, E223 and E224.

But the comma is a delimiter, not an operator. It binds less strongly than an operator.
Sometimes it may be a good idea to use extraneous whitespace for readability.

Additionally, I found this obvious example in the Python language reference.
http://docs.python.org/dev/py3k/reference/lexical_analysis.html#implicit-line-joining

month_names = ['Januari', 'Februari', 'Maart',      # These are the
               'April',   'Mei',      'Juni',       # Dutch names
               'Juli',    'Augustus', 'September',  # for the months
               'Oktober', 'November', 'December']   # of the year

So, I propose to lift the check E241.

Spurious E701 and E225 for function annotations

The following program:

!/usr/bin/python3

def foo(x: int) -> int:
return x + 1

results in the warnings:

pep8.py:4:10: E701 multiple statements on one line (colon)
pep8.py:4:18: E225 missing whitespace around operator

The first spurious warning seems to come from the annotated argument, and the second seems to come from the annotated return value.

pep8 crashes on incomplete python script

pep8 should catch this TokenError and report it as another problem, not crash. With the input file of just 'a(', pep8 crashes as such (v1.0.1):

Traceback (most recent call last):
File "/usr/bin/pep8", line 9, in
load_entry_point('pep8==1.0.1', 'console_scripts', 'pep8')()
File "/usr/lib/python2.7/dist-packages/pep8.py", line 1348, in _main
runner(path)
File "/usr/lib/python2.7/dist-packages/pep8.py", line 1023, in input_file
errors = Checker(filename).check_all()
File "/usr/lib/python2.7/dist-packages/pep8.py", line 949, in check_all
for token in tokenize.generate_tokens(self.readline_check_physical):
File "/usr/lib/python2.7/tokenize.py", line 357, in generate_tokens
raise TokenError, ("EOF in multi-line statement", (lnum, 0))
tokenize.TokenError: ('EOF in multi-line statement', (2, 0))

PyPI release has multiple version identifiers

First, thanks for updating this great tool!

One little niggle though. The new 0.6.0 release on PyPI seems a little confused about which version it actually is.

Version 0.6.0 in setup.py, version 0.5.1dev in pep8.py, version 1.0.0 in ChangeLog.

Allowing a newline before ) ] or }

Hi,

I noticed that pep8.py complains about the following style:

result = func(
    arg1='some value',
    arg2='another value'
)

With the following error:
E202 whitespace before ')'

Even though there is nothing in PEP 8 against it. But if I add a comma after the last argument like this:
result = func(
arg1='some value',
arg2='another value',
)

pep8.py doesn't complain at all. Is this an intended behavior? The same applies to } or ].
This style is sometimes used inside the standard Python module library. I think that pep8.py should allow this style since there is nothing against it in PEP 8.

Thanks,
Nadia

Avoid Extraneous Whitespace Around Keywords

The current code catches whitespace issues around operators but not around keywords.

The proposal is to add a new error-class, 27X which would contain whitespace errors related to keywords. The implementation would be done in a very smilar way to operators.

"missing whitespace around operator" when returning a lambda

(Reported to me by someone else by mail)

The first of the following lines gets complained about:

       return (lambda *args, **kw:
               self._negate(assertion, *args, **kw))

1 selenese.py:235 col 29: E225 missing whitespace around operator
2 selenese.py:241 col 29: E225 missing whitespace around operator

nested def: 0 whitelines found

Possible glitch reported by someone else to me by mail:

def assert_type(type):
   def decorate(func):

This complains:

selenese.py:28 col 5: E301 expected 1 blank line, found 0

(we need to check whether that's valid or invalid)

E241 false negative

I recall noticing this quite a while ago.

locale_encoding_alias = {
    'ascii': 'ISO8859-1',
    'latin_1':                      'ISO8859-1',
    'iso8859_1':                    'ISO8859-1',
}
$ pep8 locale_example.py --ignore=E1,E7,E501

Expected:

locale_example.py:3:15: E241 multiple spaces after ':'
locale_example.py:4:17: E241 multiple spaces after ':'

Got:

locale_example.py:3:15: E241 multiple spaces after ':'

Do not require a blank line before an indented block.

The following snippets should not yield an E301 (blank line missing).

try:
    from nonexistent import Bar
except ImportError:
    class Bar(object):
        """This is a Bar replacement"""

def with_feature(f):
    """Some decorator"""
    wrapper = f
    if has_this_feature(f):
        def wrapper(*args):
            call_feature(args[0])
            return f(*args)
    return wrapper

try:
    next
except NameError:
    def next(iterator, default):
        for item in iterator:
            return item
        return default

Spurious "redefinition of function" reported with @property decorator

As of Python 2.6, the property() built-in supports use as a decorator (see http://docs.python.org/library/functions.html#property):

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Unfortunately, this syntax requires the use of the functions to have the same name, which triggers the "redefinition of function" warning.

--count seems to clash with --ignore

Example:
rapid: md$ make cleanup
./pythonenv/bin/pep8 --count --repeat --ignore=E501,E301,E302,E303 www
158
make: *** [cleanup] Error 1

It seems that get_count() also counts the explicitly ignored erros

Incorrect line number on E303 errors on test files

When running the E30.py test file I noticed an incorrect message. I boiled it down to a simple example. If you use the following example:

print
#: E303
def a():
    print


    # comment

    print
#:

When you run pep8 on it you get:

test2.py:3:1: E302 expected 2 blank lines, found 0
test2.py:9:5: E303 too many blank lines (2>1)

If you notice the first report is genuine but the second report says 2>1 but points to the line for print. First that is 1 blank line not 2 and second the violation is actually on 7 the comment line. When you manually remove line 6 it no longer detects the error as expected. So it seems it's a problem with the line number reported.

--repeat is not the default

this one es rather painfull
even more so in multi-file context

also there hardly seems to be a reason not to make it the default
all errors at once is vastly more helpfull

always exit with worthful status code

I am going to use pep8 with my continuous integration server and I would like pep8 exits with worthful status code, so I can check if there were warnings/errors or the code was 100% ok.

Well, while I don't fork and do that, other could do ;-)
Cheers,
Hugo.

False positive for E502

blah.py:

('\
    ' + ' \
')
$ ./pep8.py blah.py
blah.py:2:11: E502 the backslash is redundant between brackets

suport configuring th output file

this would ease integrating with normal test collection, where one pep8 tests one file at a time recording all errors

currently i need to monkeypatch sys.stdout

blank line at end of file

What is more 'pythonic' - to leave blank line at end of file or not? Most tools require blank line at end of file. There is no ugly message "\ No newline at end of file" in diff output. Why does pep8 tool require no blank lines at end of file?

Uncaught exception on really bad indentation

Steps to reproduce:

Run against the following code:

while True:
    try:
⇥    pass
⇥except:
⇥⇥print 'Whoops'

(Note the arrangement of tabs and spaces.)

This causes pep8 to fall over with an uncaught exception:

Traceback (most recent call last):
  File "/usr/local/bin/pep8", line 8, in 
    load_entry_point('pep8==0.6.1', 'console_scripts', 'pep8')()
  File "/Library/Python/2.6/site-packages/pep8.py", line 1346, in _main
    runner(path)
  File "/Library/Python/2.6/site-packages/pep8.py", line 1027, in input_file
    errors = Checker(filename).check_all()
  File "/Library/Python/2.6/site-packages/pep8.py", line 953, in check_all
    for token in tokenize.generate_tokens(self.readline_check_physical):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tokenize.py", line 346, in generate_tokens
    ("", lnum, pos, line))
  File "", line 4
    except:
    ^
IndentationError: unindent does not match any outer indentation level

Checking variable comparisons to None, True, and False not implemented

The None, True, and False values are singletons.

All variable comparisons to singletons should use 'is' or 'is not'.
All variable evaluations to boolean should use 'if' or 'if not'.

"== None", "== True", "== False", and "!= None" comparisons in sqlalchemy's
where(), or_(), filter(), and_(), and select() functions should not be changed.

Incorrect comparisons or evaluations in comments should be ignored.

E502 malfunction

            (""";item 1:definition 1
;item 2:definition 2
""", u'''\
<page><body>\
...

It thinks that the backslash at the end of the 3rd line is redundant, which is definitely wrong as it avoids that the linefeed gets into the multiline string.

moin-2.0/MoinMoin/converter/_tests/test_mediawiki_in.py:72:10: E502 the backslash is redundant between brackets
""", u'''\

Automatically fix reported issues

On most occasions fixing the errors reported by pep8 is pretty straightforward. Would be cool if the tool could patch the source code automatically, not merely report (or maybe there's another script that already does that?)

E211 not raised

Following line should trigger E211

dict['key'] ['subkey'] = value

Should not flag desirable trailing white space (embedded functions)

In this code:

def asciify(data):
    def _asciify_list(data):
        """ Ascii-fies list values """
        ret = []
        for item in data:
            if isinstance(item, unicode):
                item = item.encode('utf-8')
            elif isinstance(item, list):
                item = _asciify_list(item)
            elif isinstance(item, dict):
                item = _asciify_dict(item)
            ret.append(item)
        return ret

    ## above line has 4 leading spaces, gets W291 warning
    def _asciify_dict(data):
        """ Ascii-fies dict keys and values """
        ret = {}
        for key, value in data.iteritems():
            if isinstance(key, unicode):
                key = key.encode('utf-8')
            ## note new if
            if isinstance(value, unicode):
                value = value.encode('utf-8')
            elif isinstance(value, list):
                value = _asciify_list(value)
            elif isinstance(value, dict):
                value = _asciify_dict(value)
            ret[key] = value
        return ret

    ## above line has 4 leading spaces, gets W291 warning
    if isinstance(data, list):
        return _asciify_list(data)
    elif isinstance(data, dict):
        return _asciify_dict(data)
    elif isinstance(data, unicode):
        return data.encode('utf-8')
    elif isinstance(data, str):
        return data
    else:
        raise TypeError("Input must be dict, list or str")

asciify_list and asciify_dict are nested functions. The last 10 lines are the main body of the function.

See the commented lines -- the line above each comment has 4 space characters, which I use intentionally.

The spaces are desirable, since copying the function from source / pasting into an interactive Python prompt without these spaces results in indentation errors. A totally blank line is interpreted as end of the (top-level) function definition. What is needed is end of nested function definition, which naturally is at the same indent level as the main body of the function.

Bottom line, seems the trailing whitespace rule should require trailing whitespace equal to the indent level of the nested function.

Otherwise, we have to choose between spurious pep8 errors and not being able to copy-paste code into the interpreter.

Detecting unassigned triple quoted strings

Python doesn't provide a way to do block quotes other than prefixing all lines in a block with # .
Some people find this "too complicated" and have started to use triple quotes (""" or ''') to achieve a block quote like behavior.

Although not explicitly stated in PEP8, this is considered by many bad practice and in some occasions confusion about how docstrings work.

In light of this, I propose that triple quotes that are not docstrings, are not assigned to variables, nor contained in (), [] or {}, are treated as errors or raise a warning.

Add a --max-line-length option.

PEP8 states "There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side."

This might have been true in 2001 when PEP8 was written but with display sizes and screen resolutions in 2011 there is little reason to stay at 80 characters. We therefore choose to go for 110 chars per line reducing the pressure to use short function and variable names somewhat. From looking at other projects it seems to me that 80 chars per line is slowly loosing.

This forces us currently to run pep8 with the --ignore=E501 option. pylint instead comes with a --max-line-length option. I would love to see such an option very much also in pep8.

There is a patch from Mike Koss at mckoss@0351c99#diff-2 which implements exactly this.

It would be great if that could be included in the next release.

Regardless of line-length: Thanks for all the work with pep8!

Make it easier to use as a module rather than a script

For writing (say) git/hg hooks, it'd much more convenient to be able to import pep8 as a module and use it inline, rather than having to shell out to run it as a script, capture and parse the output, etc.

This would require some fairly non-trivial changes -- e.g. there's currently lots of inline printing and a global options variable -- and there would be some api decisions to make.

I might take a look at putting together a pull request if there is interest...is there?

Numpy array slice notation

I'm having a problem with files that use Numpy slice notation. Here is an example:

import numapy as np
a = np.zeros(2, 2)
print a[0, :]

will give the following error:

E203 : whitespace before ':'

and

import numpy as np
a = np.zeros(2, 2)
print a[0,:]

will give the following error:

E231 : missing whitespace after ','

Is there a way to get around this?

E225 false positive

I noticed this a while back (and put an exception for it in autopep8).

if True:
    # Python 3
    *a, b = (1, 2, 3)
blah.py:3:5: E225 missing whitespace around operator

Spurious E301 for nested function definitions

Simple nested functions without preceeding blank line are not a violation of PEP 8. It is up to the human to decide readability in this case.

pep8-0.6.1 will emit errors in cases where an extra blank line is not required or appropriate.

Example code, pep8_bug.py:

"""Demonstrate bug"""


def safe_accessors(dictionary=False):
    """simplified from complex test code..."""
    if dictionary:
        _setattr, _getattr, _delattr = setitem, getitem, delitem
        def _hasattr(_dict, value):
            return value in _dict
    else:
        _setattr, _getattr, _delattr, _hasattr = (
            setattr, getattr, delattr, hasattr
        )
    return _setattr, _getattr, _delattr, _hasattr

pep8 output:

pep8_bug.py:9:9: E301 expected 1 blank line, found 0

The correct output is to be silent (or at most emit a silence-able warning).

Reference: "PEP 8" / "Code lay-out" / "Blank Lines"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.