/Lib/lib2to3/fixes/fix_filter.py

http://unladen-swallow.googlecode.com/ · Python · 75 lines · 52 code · 1 blank · 22 comment · 0 complexity · 0879d4b1af4eeb93b1a8baff1fd298c1 MD5 · raw file

  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer that changes filter(F, X) into list(filter(F, X)).
  4. We avoid the transformation if the filter() call is directly contained
  5. in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or
  6. for V in <>:.
  7. NOTE: This is still not correct if the original code was depending on
  8. filter(F, X) to return a string if X is a string and a tuple if X is a
  9. tuple. That would require type inference, which we don't do. Let
  10. Python 2.6 figure it out.
  11. """
  12. # Local imports
  13. from ..pgen2 import token
  14. from .. import fixer_base
  15. from ..fixer_util import Name, Call, ListComp, in_special_context
  16. class FixFilter(fixer_base.ConditionalFix):
  17. PATTERN = """
  18. filter_lambda=power<
  19. 'filter'
  20. trailer<
  21. '('
  22. arglist<
  23. lambdef< 'lambda'
  24. (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
  25. >
  26. ','
  27. it=any
  28. >
  29. ')'
  30. >
  31. >
  32. |
  33. power<
  34. 'filter'
  35. trailer< '(' arglist< none='None' ',' seq=any > ')' >
  36. >
  37. |
  38. power<
  39. 'filter'
  40. args=trailer< '(' [any] ')' >
  41. >
  42. """
  43. skip_on = "future_builtins.filter"
  44. def transform(self, node, results):
  45. if self.should_skip(node):
  46. return
  47. if "filter_lambda" in results:
  48. new = ListComp(results.get("fp").clone(),
  49. results.get("fp").clone(),
  50. results.get("it").clone(),
  51. results.get("xp").clone())
  52. elif "none" in results:
  53. new = ListComp(Name("_f"),
  54. Name("_f"),
  55. results["seq"].clone(),
  56. Name("_f"))
  57. else:
  58. if in_special_context(node):
  59. return None
  60. new = node.clone()
  61. new.set_prefix("")
  62. new = Call(Name("list"), [new])
  63. new.set_prefix(node.get_prefix())
  64. return new