1# Copyright 2008 Armin Ronacher.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Fixer that cleans up a tuple argument to isinstance after the tokens
5in it were fixed.  This is mainly used to remove double occurrences of
6tokens as a leftover of the long -> int / unicode -> str conversion.
7
8eg.  isinstance(x, (int, long)) -> isinstance(x, (int, int))
9       -> isinstance(x, int)
10"""
11
12from .. import fixer_base
13from ..fixer_util import token
14
15
16class FixIsinstance(fixer_base.BaseFix):
17    BM_compatible = True
18    PATTERN = """
19    power<
20        'isinstance'
21        trailer< '(' arglist< any ',' atom< '('
22            args=testlist_gexp< any+ >
23        ')' > > ')' >
24    >
25    """
26
27    run_order = 6
28
29    def transform(self, node, results):
30        names_inserted = set()
31        testlist = results["args"]
32        args = testlist.children
33        new_args = []
34        iterator = enumerate(args)
35        for idx, arg in iterator:
36            if arg.type == token.NAME and arg.value in names_inserted:
37                if idx < len(args) - 1 and args[idx + 1].type == token.COMMA:
38                    iterator.next()
39                    continue
40            else:
41                new_args.append(arg)
42                if arg.type == token.NAME:
43                    names_inserted.add(arg.value)
44        if new_args and new_args[-1].type == token.COMMA:
45            del new_args[-1]
46        if len(new_args) == 1:
47            atom = testlist.parent
48            new_args[0].prefix = atom.prefix
49            atom.replace(new_args[0])
50        else:
51            args[:] = new_args
52            node.changed()
53