pycqa / pycodestyle Goto Github PK
View Code? Open in Web Editor NEWSimple Python style checker in one Python file
Home Page: https://pycodestyle.pycqa.org
License: Other
Simple Python style checker in one Python file
Home Page: https://pycodestyle.pycqa.org
License: Other
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?
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.
(""";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'''\
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?
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
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?)
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.
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.
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
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))
The last release in this repository 0.6.0.
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.
Simple patch.
211c211
< length = len(physical_line.rstrip())
length = len(unicode(physical_line.rstrip(), 'utf-8'))
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!
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.
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.
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
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.
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.
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
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.
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)
If I have a multi-line string (in triple quotes), I don't believe that pep8 should be analyzing the contents for indentation problems and the like. This code may very well be not-python and, as such, need not comply to pep8. It might be nice (though I am not certain of how easy) to treat docstrings different from other block quotes as there are guidelines on docstrings in PEP 257: http://www.python.org/dev/peps/pep-0257/
$ cat test
a, b = func(kw='k')
(a, b) = func(kw='k')
$ pep8 --repeat test
test:2:17: E225 missing whitespace around operator
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
Some projects like http://python3wos.appspot.com/ are using the classifier to see if a library is Python 3 compatible or not and pep8 doesn't have any of them.
e.g.
Programming Language :: Python :: 2
Programming Language :: Python :: 3
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
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 . $
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. :)
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
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
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.
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:
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
For example:
def test(a, b):
c = do_something(locals())
return True
Warning for unused variable should be issued only for c, not also a and b.
(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
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?
Actually file names in reports are relative but some tools works better with absolute file names, like Vim. Here a fork[1] which add '--absolute' command line option to achieve this.
[1] fork: http://github.com/mgiusti/pep8
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.
It would be nice to have an rc file to specify regularly used options, etc. (currently using shell command alias).
Thanks.
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"
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.
Following line should trigger E211
dict['key'] ['subkey'] = value
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.
The following program:
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.
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.
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
blah.py:
('\
' + ' \
')
$ ./pep8.py blah.py
blah.py:2:11: E502 the backslash is redundant between brackets
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 ':'
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.