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