Update docs for configuration
[third_party/pep8] / docs / advanced.rst
1 .. currentmodule:: pep8
2
3 ==============
4 Advanced usage
5 ==============
6
7
8 Automated tests
9 ---------------
10
11 You can also execute `pep8` tests from Python code.  For example, this
12 can be highly useful for automated testing of coding style conformance
13 in your project::
14
15   import unittest
16   import pep8
17
18
19   class TestCodeFormat(unittest.TestCase):
20
21       def test_pep8_conformance(self):
22           """Test that we conform to PEP8."""
23           pep8style = pep8.StyleGuide(quiet=True)
24           result = pep8style.check_files(['file1.py', 'file2.py'])
25           self.assertEqual(result.total_errors, 0,
26                            "Found code style errors (and warnings).")
27
28 If you are using `nosetests` for running tests, remove `quiet=True`
29 since Nose suppresses stdout.
30
31 There's also a shortcut for checking a single file::
32
33   import pep8
34
35   fchecker = pep8.Checker('testsuite/E27.py', show_source=True)
36   file_errors = fchecker.check_all()
37
38   print("Found %s errors (and warnings)" % file_errors)
39
40
41 Skip file header
42 ----------------
43
44 Another example is related to the `feature request #143
45 <https://github.com/jcrocholl/pep8/issues/143>`_: skip a number of lines
46 at the beginning and the end of a file.  This use case is easy to implement
47 through a custom wrapper for the PEP 8 library::
48
49   #!python
50   import pep8
51
52   LINES_SLICE = slice(14, -20)
53
54   class PEP8(pep8.StyleGuide):
55       """This subclass of pep8.StyleGuide will skip the first and last lines
56       of each file."""
57
58       def input_file(self, filename, lines=None, expected=None, line_offset=0):
59           if lines is None:
60               assert line_offset == 0
61               line_offset = LINES_SLICE.start or 0
62               lines = pep8.readlines(filename)[LINES_SLICE]
63           return super(PEP8, self).input_file(
64               filename, lines=lines, expected=expected, line_offset=line_offset)
65
66   if __name__ == '__main__':
67       pep8style = PEP8(parse_argv=True, config_file=True)
68       report = pep8style.check_files()
69       if report.total_errors:
70           raise SystemExit(1)
71
72 This module declares a lines' window which skips 14 lines at the beginning
73 and 20 lines at the end.  If there's no line to skip at the end, it could be
74 changed with ``LINES_SLICE = slice(14, None)`` for example.
75
76 You can save it in a file and use it with the same options as the
77 original ``pep8``.