/Doc/library/tokenize.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 121 lines · 86 code · 35 blank · 0 comment · 0 complexity · dd9f5c7cf5acf0f4604d65630437195c MD5 · raw file

  1. :mod:`tokenize` --- Tokenizer for Python source
  2. ===============================================
  3. .. module:: tokenize
  4. :synopsis: Lexical scanner for Python source code.
  5. .. moduleauthor:: Ka Ping Yee
  6. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  7. The :mod:`tokenize` module provides a lexical scanner for Python source code,
  8. implemented in Python. The scanner in this module returns comments as tokens as
  9. well, making it useful for implementing "pretty-printers," including colorizers
  10. for on-screen displays.
  11. The primary entry point is a :term:`generator`:
  12. .. function:: generate_tokens(readline)
  13. The :func:`generate_tokens` generator requires one argument, *readline*,
  14. which must be a callable object which provides the same interface as the
  15. :meth:`readline` method of built-in file objects (see section
  16. :ref:`bltin-file-objects`). Each call to the function should return one line
  17. of input as a string.
  18. The generator produces 5-tuples with these members: the token type; the token
  19. string; a 2-tuple ``(srow, scol)`` of ints specifying the row and column
  20. where the token begins in the source; a 2-tuple ``(erow, ecol)`` of ints
  21. specifying the row and column where the token ends in the source; and the
  22. line on which the token was found. The line passed (the last tuple item) is
  23. the *logical* line; continuation lines are included.
  24. .. versionadded:: 2.2
  25. An older entry point is retained for backward compatibility:
  26. .. function:: tokenize(readline[, tokeneater])
  27. The :func:`tokenize` function accepts two parameters: one representing the input
  28. stream, and one providing an output mechanism for :func:`tokenize`.
  29. The first parameter, *readline*, must be a callable object which provides the
  30. same interface as the :meth:`readline` method of built-in file objects (see
  31. section :ref:`bltin-file-objects`). Each call to the function should return one
  32. line of input as a string. Alternately, *readline* may be a callable object that
  33. signals completion by raising :exc:`StopIteration`.
  34. .. versionchanged:: 2.5
  35. Added :exc:`StopIteration` support.
  36. The second parameter, *tokeneater*, must also be a callable object. It is
  37. called once for each token, with five arguments, corresponding to the tuples
  38. generated by :func:`generate_tokens`.
  39. All constants from the :mod:`token` module are also exported from
  40. :mod:`tokenize`, as are two additional token type values that might be passed to
  41. the *tokeneater* function by :func:`tokenize`:
  42. .. data:: COMMENT
  43. Token value used to indicate a comment.
  44. .. data:: NL
  45. Token value used to indicate a non-terminating newline. The NEWLINE token
  46. indicates the end of a logical line of Python code; NL tokens are generated when
  47. a logical line of code is continued over multiple physical lines.
  48. Another function is provided to reverse the tokenization process. This is useful
  49. for creating tools that tokenize a script, modify the token stream, and write
  50. back the modified script.
  51. .. function:: untokenize(iterable)
  52. Converts tokens back into Python source code. The *iterable* must return
  53. sequences with at least two elements, the token type and the token string. Any
  54. additional sequence elements are ignored.
  55. The reconstructed script is returned as a single string. The result is
  56. guaranteed to tokenize back to match the input so that the conversion is
  57. lossless and round-trips are assured. The guarantee applies only to the token
  58. type and token string as the spacing between tokens (column positions) may
  59. change.
  60. .. versionadded:: 2.5
  61. Example of a script re-writer that transforms float literals into Decimal
  62. objects::
  63. def decistmt(s):
  64. """Substitute Decimals for floats in a string of statements.
  65. >>> from decimal import Decimal
  66. >>> s = 'print +21.3e-5*-.1234/81.7'
  67. >>> decistmt(s)
  68. "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"
  69. >>> exec(s)
  70. -3.21716034272e-007
  71. >>> exec(decistmt(s))
  72. -3.217160342717258261933904529E-7
  73. """
  74. result = []
  75. g = generate_tokens(StringIO(s).readline) # tokenize the string
  76. for toknum, tokval, _, _, _ in g:
  77. if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens
  78. result.extend([
  79. (NAME, 'Decimal'),
  80. (OP, '('),
  81. (STRING, repr(tokval)),
  82. (OP, ')')
  83. ])
  84. else:
  85. result.append((toknum, tokval))
  86. return untokenize(result)