fix_ws_comma.py 1.06 KB
Newer Older
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
11

12
class FixWsComma(fixer_base.BaseFix):
13

14 15 16 17 18 19 20 21 22 23 24 25
    explicit = True # The user must ask for this fixers

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

    COMMA = pytree.Leaf(token.COMMA, ",")
    COLON = pytree.Leaf(token.COLON, ":")
    SEPS = (COMMA, COLON)

    def transform(self, node, results):
        new = node.clone()
26
        comma = False
27 28
        for child in new.children:
            if child in self.SEPS:
29
                prefix = child.prefix
30
                if prefix.isspace() and "\n" not in prefix:
31
                    child.prefix = ""
32 33 34
                comma = True
            else:
                if comma:
35
                    prefix = child.prefix
36
                    if not prefix:
37
                        child.prefix = " "
38 39
                comma = False
        return new