fix_ws_comma.py 1.07 KB
Newer Older
Martin v. Löwis's avatar
Martin v. Löwis committed
1 2 3 4 5 6 7 8 9
"""Fixer that changes 'a ,b' into 'a, b'.

This also changes '{a :b}' into '{a: b}', but does not touch other
uses of colons.  It does not touch other uses of whitespace.

"""

from .. import pytree
from ..pgen2 import token
10
from .. import fixer_base
Martin v. Löwis's avatar
Martin v. Löwis committed
11

12
class FixWsComma(fixer_base.BaseFix):
Martin v. Löwis's avatar
Martin v. Löwis committed
13

14 15 16 17 18 19
    explicit = True # The user must ask for this fixers

    PATTERN = """
    any<(not(',') any)+ ',' ((not(',') any)+ ',')* [not(',') any]>
    """

20 21
    COMMA = pytree.Leaf(token.COMMA, u",")
    COLON = pytree.Leaf(token.COLON, u":")
22 23 24 25
    SEPS = (COMMA, COLON)

    def transform(self, node, results):
        new = node.clone()
Martin v. Löwis's avatar
Martin v. Löwis committed
26
        comma = False
27 28
        for child in new.children:
            if child in self.SEPS:
Benjamin Peterson's avatar
Benjamin Peterson committed
29
                prefix = child.prefix
30
                if prefix.isspace() and u"\n" not in prefix:
Benjamin Peterson's avatar
Benjamin Peterson committed
31
                    child.prefix = u""
32 33 34
                comma = True
            else:
                if comma:
Benjamin Peterson's avatar
Benjamin Peterson committed
35
                    prefix = child.prefix
36
                    if not prefix:
Benjamin Peterson's avatar
Benjamin Peterson committed
37
                        child.prefix = u" "
38 39
                comma = False
        return new