[Python] W293 blank line contains whitespace

Marco Giusti marco.giusti a gmail.com
Ven 24 Maggio 2013 14:34:17 CEST


On Fri, May 24, 2013 at 02:12:09PM +0200, Marco Beri wrote:
> 2013/5/24 Nicola Larosa <nico a teknico.net>
> 
> > Pietro Battiston wrote:
> > > Ma ce n'č una per cui non mi do pace.
> > >
> > > Ho sempre usato l'indentazione nelle linee vuote, corrispondente al
> > > contesto - es. 4 spazi per separare i metodi di una classe, 8 per
> > > separare le righe di codice dei metodi, 12 per separare righe di
> > > codice all'interno di un ciclo all'interno di un metodo ecc ecc...
> >
> > Una volta lo facevo anch'io, poi ho capito. :-)
> >
> 
> Da sempre il mio vi mi fa questo:
> http://troll.ws/image/633baf74#.UZ9YWysW3RE

esitavo a postare queste poche righe ma visto che non sono l'unico ad
usare certi editor ecco una sintesi della mia configurazione di vim,
specifica per python, che puņ essere utile a qualcuno. in allegato i
file da aggiungere in ~/.vim/compiler/

	# in ~/.vimrc
	set tabstop=4
	set softtabstop=4
	set shiftwidth=4
	set autowrite

	noremap <F2> <Esc>:compiler pep8<CR>:make<CR>
	noremap <F3> <Esc>:compiler pyflakes<CR>:make<CR>
	noremap <F4> <Esc>:compiler unit2<CR>:make<CR>
	noremap <F6> <Esc>:cp<CR>
	noremap <F7> <Esc>:cn<CR>

	autocmd FileType python set textwidth=79 smarttab expandtab number
	let python_highlight_all = 1				" sintassi python
	autocmd BufWritePre *.py %s/\s\+$//e		" Trim ending spaces
-------------- parte successiva --------------
" Vim Compiler file
" Compiler: pep8
" Maintainer: Marco Giusti <marco.giusti a gmail.com>
" Last Change: 2010-06-03

if exists("current_compiler")
    finish
endif
let current_compiler = "pep8"

if exists(":CompilerSet") != 2
    command -nargs=* CompilerSet setlocal <args>
endif
CompilerSet efm=%f:%l:%c:\ %m
CompilerSet makeprg=pep8\ %

-------------- parte successiva --------------
if exists("current_compiler")
    finish
endif
let current_compiler = "pyflakes"

if exists(":CompilerSet") != 2
    command -nargs=* CompilerSet setlocal <args>
endif
CompilerSet efm=%f:%l:\ %m
CompilerSet makeprg=pyflakes\ %
-------------- parte successiva --------------
" Vim Compiler file
" Compiler: py.test
" Maintainer: Marco Giusti <marco.giusti a gmail.com>
" Last Change: 2010-06-03

if exists("current_compiler")
    finish
endif
let current_compiler = "pyunit"

if exists(":CompilerSet") != 2
    command -nargs=* CompilerSet setlocal <args>
endif
CompilerSet efm=%f:%l:\ %m
CompilerSet makeprg=pyunit\ --testmodule\ %

-------------- parte successiva --------------
#!/usr/bin/env python

import os
import sys
import types
import traceback
if sys.hexversion >= 0x02070000:
    import unittest
else:
    import unittest2 as unittest
import imp


# The following lines are copyrighted by Twisted Matrix Laboratories.
# Copyright (c) 2001-2007 Twisted Matrix Laboratories.

def _parseLocalVariables(line):
    """Accepts a single line in Emacs local variable declaration format and
    returns a dict of all the variables {name: value}.
    Raises ValueError if 'line' is in the wrong format.

    See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
    """
    paren = '-*-'
    start = line.find(paren) + len(paren)
    end = line.rfind(paren)
    if start == -1 or end == -1:
        raise ValueError("%r not a valid local variable declaration" % (line,))
    items = line[start:end].split(';')
    localVars = {}
    for item in items:
        if len(item.strip()) == 0:
            continue
        split = item.split(':')
        if len(split) != 2:
            raise ValueError("%r contains invalid declaration %r"
                             % (line, item))
        localVars[split[0].strip()] = split[1].strip()
    return localVars


def loadLocalVariables(filename):
    """Accepts a filename and attempts to load the Emacs variable declarations
    from that file, simulating what Emacs does.

    See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
    """
    f = file(filename, "r")
    lines = [f.readline(), f.readline()]
    f.close()
    for line in lines:
        try:
            return _parseLocalVariables(line)
        except ValueError:
            pass
    return {}


def getTestModules(filename):
    testCaseVar = loadLocalVariables(filename).get('test-case-name', None)
    if testCaseVar is None:
        return []
    return testCaseVar.split(',')


def _importFromFile(fn, moduleName=None):
    fn = _resolveDirectory(fn)
    if not moduleName:
        moduleName = os.path.splitext(os.path.split(fn)[-1])[0]
    if moduleName in sys.modules:
        return sys.modules[moduleName]
    fd = open(fn, 'r')
    try:
        module = imp.load_source(moduleName, fn, fd)
    finally:
        fd.close()
    return module


def _resolveDirectory(fn):
    if os.path.isdir(fn):
        initFile = isPackageDirectory(fn)
        if initFile:
            fn = os.path.join(fn, initFile)
        else:
            raise ValueError('%r is not a package directory' % (fn,))
    return fn


def isPackageDirectory(dirname):
    """Is the directory at path 'dirname' a Python package directory?
    Returns the name of the __init__ file (it may have a weird extension)
    if dirname is a package directory.  Otherwise, returns False"""
    for ext in zip(*imp.get_suffixes())[0]:
        initFile = '__init__' + ext
        if os.path.exists(os.path.join(dirname, initFile)):
            return initFile
    return False


class LineTextTestResult(unittest.TextTestResult):

    def _exc_info_to_string(self, err, test):
        """Converts a sys.exc_info()-style tuple of values into a string."""
        exctype, value, tb = err
        # Skip test runner traceback levels
        while tb and self._is_relevant_tb_level(tb):
            tb = tb.tb_next

        if exctype is test.failureException:
            # Skip assert*() traceback levels
            length = self._count_relevant_tb_levels(tb)
            msgLines = traceback.format_exception(exctype, value, tb, length)
        else:
            msgLines = traceback.format_exception(exctype, value, tb)

        if self.buffer:
            output = sys.stdout.getvalue()
            error = sys.stderr.getvalue()
            if output:
                if not output.endswith('\n'):
                    output += '\n'
                msgLines.append(STDOUT_LINE % output)
            if error:
                if not error.endswith('\n'):
                    error += '\n'
                msgLines.append(STDERR_LINE % error)
        if tb:
            f = tb.tb_frame
            lineno = tb.tb_lineno
            co = f.f_code
            filename = co.co_filename
            msg = ''.join(traceback.format_exception_only(exctype, value))
            msgLines.append('\n%s:%s:%s' % (filename, lineno, msg))
        return ''.join(msgLines)


def loadModule(modulename):
    parts = modulename.split('.')
    fp = paths = None
    try:
        while parts:
            name = parts.pop(0)
            fp, path, (suf, mode, tpe) = imp.find_module(name, paths)
            if tpe not in (imp.PKG_DIRECTORY, imp.PY_SOURCE):
                raise ImportError('Invalid module type')
            module = imp.load_module(name, fp, path, (suf, mode, tpe))
            if tpe == imp.PY_SOURCE:
                return module
            else:  # tpe == imp.PKG_DIRECTORY
                paths = module.__path__
                if not parts:
                    raise ImportError('Packages not accepted')
    finally:
        if fp is not None:
            fp.close()


def isTestFile(filename):
    """Returns true if 'filename' looks like a file containing unit tests.
    False otherwise.  Doesn't care whether filename exists.
    """
    basename = os.path.basename(filename)
    return (basename.startswith('test_')
            and os.path.splitext(basename)[1] == ('.py'))


def _format_final_exc_line(etype, value):
    """Return a list of a single line --
    normal case for format_exception_only"""
    valuestr = traceback._some_str(value)
    if value is None or not valuestr:
        line = ' %s' % etype
    else:
        line = " %s: %s" % (etype, valuestr)
    return line
traceback._format_final_exc_line = _format_final_exc_line


if __name__ == '__main__':
    argv = []
    argv_copy = sys.argv[:]
    module = None
    buffer = False
    while argv_copy:
        arg = argv_copy.pop(0)
        if arg in ('-g', '--testmodule'):
            filename = argv_copy.pop(0)
            if isTestFile(filename):
                module = _importFromFile(filename)
            else:
                argv.extend(getTestModules(filename))
        elif arg in ("-b", "--buffer"):
            buffer = True
        else:
            argv.append(arg)

    runner = unittest.TextTestRunner(buffer=buffer,
                                     resultclass=LineTextTestResult)
    unittest.main(module, argv=argv, testRunner=runner)


Maggiori informazioni sulla lista Python