Package: pep8radius
pep8radiusPEP8clean only the
parts of the files touched since the last commit, a previous commit or
(the merge-base of) a branch.Fixing the entire project of PEP8 infractions (“PEP8 storms”) can lead
to merge conflicts, add noise to merges / pull requests and break (git)
blame. pep8radius solves this problem by fixing only those PEP8
infractions incontained on the lines of the project which you’ve been
working, leaving these sections “better than you found it” whilst
keeping your commits focused on the areas of the codebase you were
actually working on.Requirementspep8radius usesautopep8,
and in turnpep8. The
docformatter option, to fix docstrings, usesdocformatter.You can also useyapfas an
alternative back-end.InstallationFrom pip:$pipinstallpep8radiusUsageUsage gif of pep8radiusMove to project directoryMake some changes to the projectRunpep8radius--diff# view a diff of proposed fixedRunpep8radius--in-place# apply the fixesCommit your changesAgainst a branch you can use the same syntax as with git diff:$pep8radiusmaster# branch name to compare against (compares against merge-base)$pep8radiusc12166f# commit hash$pep8radiusmaster--in-place# these work with other options tooYou can also fix docstrings
(PEP257) using thedocformatteroption:$pep8radius--docformatter--diffNote: can also use ``btyfi`` alias for ``pep8radius``.It can be nice to pipe the diff tocdiff(which makes diffs pretty
and has lots of options):$pep8radius--diff--no-color|cdiff$pep8radius--diff--no-color|cdiff--side-by-sideYou can get strange results if you don’t use no-color.I actually use the following git alias (which allowsgit radandgit rad-i):[alias]rad=!pep8radiusmaster--diff--no-color$@|cdiff--side-by-sidewhich outputs the corrections as follows:git radYou can pipe in a diff directly, to fix the lines modified in it with--from-diff(this is somewhat experimental, please report failing
diffs!).For example:$gitdiffmaster|pep8radius--diff--from-diff=-yapfTo useyapfas an alternative
back-end, you can pass the--yapfoption:$ pep8radius master --diff --yapf

$ pep8radius master --diff --yapf --style=googleNote: This ignores autopep8 and docformatter specific arguments.Config Filespep8radius looks for configuration files as described in thepep8
docs.At the project level, you may have asetup.cfgwhich includes a pep8
section, you can use this to define defaults for pep8radius and
autopep8:[pep8]
rev = master
ignore = E226,E302,E41
max-line-length = 160By default, this will look for a user level default, you can suppress
this by passing a blank toglobal_config:[pep8]
rev = staging
global_config =or perhaps you want to use yapf with google style:[pep8]
rev = master
yapf = True
style = googleNote: style can also be a config file, or a dict (see the yapf docs).VCS SupportGit,Mecurial
(hg), (tentatively)Bazaar. Please request support for
other version control systems ongithub.Options$pep8radius--helpusage:pep8radius[-h][--version][-d][-i][--no-color][-v][--from-diffDIFF][-pn][-a][--experimental][--excludeglobs][--list-fixes][--ignoreerrors][--selecterrors][--max-line-lengthn][--indent-sizen][-f][--no-blank][--pre-summary-newline][--force-wrap][--global-configGLOBAL_CONFIG][--ignore-local-config][rev]PEP8cleanonlythepartsofthefileswhichyouhavetouchedsincethelastcommit,apreviouscommitor(themerge-baseof)abranch.positionalarguments:revcommitornameofbranchtocompareagainstoptionalarguments:-h,--helpshowthishelpmessageandexit--versionprintversionnumberandexit-d,--diffprintthediffoffixedsourcevsoriginal-i,--in-placemakethefixesinplace;modifythefiles--no-colordonotprintdiffsincolor(defaultistousecolor)-v,--verboseprintverbosemessages;multiple-vresultinmoreverbosemessages(oneless-vispassedtoautopep8)--from-diffDIFFExperimental:ratherthancallingouttoversioncontrol,justpassinadiff;themodifiedlineswillbefixedpep8:Pep8optionstopasstoautopep8.-pn,--pep8-passesnmaximumnumberofadditionalpep8passes(default:infinite)-a,--aggressiveenablenon-whitespacechanges;multiple-aresultinmoreaggressivechanges--experimentalenableexperimentalfixes--excludeglobsexcludefile/directorynamesthatmatchthesecomma-separatedglobs--list-fixeslistcodesforfixesandexit;usedby--ignoreand--select--ignoreerrorsdonotfixtheseerrors/warnings(default:E24)--selecterrorsfixonlytheseerrors/warnings(e.g.E4,W)--max-line-lengthnsetmaximumallowedlinelength(default:79)--indent-sizennumberofspacesperindentlevel(default4)docformatter:FixdocstringsforPEP257.-f,--docformatterUsedocformatter--no-blankDonotaddblanklineafterdescription--pre-summary-newlineaddanewlinebeforethesummaryofamulti-linedocstring--force-wrapforcedescriptionstobewrappedevenifitmayresultinamessconfig:Changedefaultoptionsbasedonglobalorlocal(project)configfiles.--global-configfilenamepathtoglobalpep8configfile;ifthisfiledoesnotexistthenthisisignored(default:~/.config/pep8)--ignore-local-configdon't look for and apply local config files; if not
                        passed, defaults are updated with any config files in
                        the project'srootdiryapf:Optionsforyapf,alternativetoautopep8.Currentlyanyotheroptionsareignored.-y,--yapfUseyapfratherthanautopep8.Thisignoresotherargumentsoutsideofthisgroup.--stylestyleeitherpep8,google,nameoffilewithstylesettings,oradictRunbeforeyoucommit,againstapreviouscommitorbranchbeforemerging.For more information about these options see
`autopep8 <https://pypi.python.org/pypi/autopep8>`__.As a modulePep8radius also exports lightweight wrappers around autopep8 so that you
can fix line ranges of your code withfix_codeorfix_file.Here’s the example “bad code” fromautopep8’s
README:importmath,sys;defexample1():####This is a long comment. This should be wrapped to fit within 72 characters.some_tuple=(1,2,3,'a');some_variable={'long':'Long code lines should be wrapped within 79 characters.','other':[math.pi,100,200,300,9876543210,'This is a long string that goes on'],'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,20,300,40000,500000000,60000000000000000]}}return(some_tuple,some_variable)defexample2():return{'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));classExample3(object):def__init__(self,bar):#Comments should have a space after the hash.ifbar:bar+=1;bar=bar*bar;returnbarelse:some_string="""
               Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""return(sys.path,some_string)You can pep8 fix just the line ranges 1-1 (the imports) and 12-21 (theExample3class) withpep8radius.fix_code(code, [(1, 1), (12,21)])(where code is a
string of the above), which returns the code fixed within those ranges:importmathimportsysdefexample1():####This is a long comment. This should be wrapped to fit within 72 characters.some_tuple=(1,2,3,'a');some_variable={'long':'Long code lines should be wrapped within 79 characters.','other':[math.pi,100,200,300,9876543210,'This is a long string that goes on'],'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,20,300,40000,500000000,60000000000000000]}}return(some_tuple,some_variable)defexample2():return{'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));classExample3(object):def__init__(self,bar):# Comments should have a space after the hash.ifbar:bar+=1bar=bar*barreturnbarelse:some_string="""
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""return(sys.path,some_string)You can usefix_fileto do this directly on a file, which gives you
the option of doing this in place.pep8radius.fix_code('code.py',[(1,1),(12,21)],in_place=True)You can also pass the same arguments to pep8radius script itself using
theparse_args. For example ignoring long lines (E501) and use the
options from your global config files:args=pep8radius.parse_args(['--ignore=E501','--ignore-local-config'],apply_config=True)pep8radius.fix_code(code,[(1,1),(12,21)],options=args)