Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Test for running PEP8 against all Python files. Useful to hook up to nose and as part of your CI. I modify PEP8 in two ways by default: don't enforce 4-spacing (I prefer 2-spacing), and use 100 for the default line length, because we don't use 80-column punch cards anymore. Licensed under CC0 (public domain): do what you want. http://creativecom…
"""Run PEP8 on all Python files in this directory and subdirectories as part of the tests."""
__author__ = 'Christopher Swenson'
__email__ = ''
__license__ = 'CC0'
import os
import os.path
import unittest
import pep8
# ignore stuff in virtualenvs or version control directories
ignore_patterns = ('.svn', 'bin', 'lib' + os.sep + 'python')
def ignore(dir):
"""Should the directory be ignored?"""
for pattern in ignore_patterns:
if pattern in dir:
return True
return False
class TestPep8(unittest.TestCase):
"""Run PEP8 on all files in this directory and subdirectories."""
def test_pep8(self):
style = pep8.StyleGuide(quiet=True)
style.options.ignore += ('E111',) # 4-spacing is just too much
style.options.max_line_length = 100 # because it isn't 1928 anymore
errors = 0
for root, _, files in os.walk('.'):
if ignore(root):
python_files = [f for f in files if f.endswith('.py')]
errors += style.check_files(python_files).total_errors
self.assertEqual(errors, 0, 'PEP8 style errors: %d' % errors)
Copy link

callmewhy commented Sep 22, 2016

@dufferzafar you are right.

And should be 'errors=' not '+=' because total errors already sum the error count.

Copy link

tram0004 commented Oct 4, 2017


Working code, reading style edits from tox.ini:

import os
import unittest
import pycodestyle

class TestPep8(unittest.TestCase):
    """Run PEP8 on all project files."""
    def test_pep8(self):
        style = pycodestyle.StyleGuide(quiet=False, config_file='tox.ini')
        for root, dirs, files in os.walk('myproject/'):
            python_files = [os.path.join(root, f) for f in files if f.endswith('.py')]
        n = style.check_files().total_errors
        self.assertEqual(n, 0, 'PEP8 style errors: %d' % n)

And tox.ini looks like this:

envlist = py34

deps = pytest
commands = {envpython} test

ignore = E501

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment